我想知道你是否可以提供帮助。我试图将变量传递给PHP文件,然后使用该变量运行SQL查询,然后将结果作为变量传回给javascript。目前,我已经成功使用Ajax将PHP返回给JavaScript,但无法将ServiceName发送到PHP文件。文件保持分离是非常重要的。也只是为了澄清我已经取代了某些部分的隐私,但是,他们是正确的,并在代码中工作。我已经使用了$ _GET方法,但是,我只能让JavaScript访问一个新窗口而不返回PHP变量。通过Javascript变量到PHP文件
我当前的代码如下:
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
// Declare the value of the new Service name and save it in the variable A.
a = sender.getValue();
{
// if it equals a new variable.
if (sender.getValue() == a) {
// Place it within the URL, in order for it to be processed in the php code.
window.location.href = "http://IP/development/Query01.php?service=" + a;
// Attempted code
// echo jason_encode(a);
// $.ajax({var service = a;
// $.post('http://IP/development/Query01.php', {variable: service});
// }
//use AJAX to retrieve the results, this does work if the service name is hard coded into the PHP.
$.ajax({
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data) { // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
}
}
}
<?php
$serverName = "SeverIP"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array("Database"=>"DatabaseName", "UID"=>"Username", "PWD"=>"Password
$conn = sqlsrv_connect($serverName, $connectionInfo);
$service = $_GET['service'];
if ($conn)
{
//echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die(print_r(sqlsrv_errors(), true));
}
$sql = ("SELECT DefaultContact2 FROM tblServices WHERE ServiceName = '$service'");
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die(print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$dC2 = $row['DefaultContact2'];
}
echo json_encode ($dC2);
sqlsrv_free_stmt($stmt);
?>
任何帮助将不胜感激。
关于将JavaScript变量发送到PHP有很多问题。例如,请参阅:http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php – trincot
另请注意,当您最初执行GET请求时尝试使用'$ .post'将不起作用 – adeneo
**警告**您的PHP代码易受SQL注入影响。不要连接变量和SQL,而是使用参数化查询:'sqlsrv_query(“SELECT DefaultContact2 FROM tblServices WHERE ServiceName =?”,array($ service));' – jcaron