这是我的JavaScript代码:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
for(i = 0; i < 5; i++)
{
var prikey = (i+1);
//document.getElementById("demo").innerHTML = prikey;
myFunction(xmlhttp.responseText);
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response)
{
//some code here
}
现在,我想将prikey从这个JavaScript文件传输到服务器端的PHP文件。
PHP代码是
$conn = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($conn,"$db_name")or die("cannot select DB");
$sql="SELECT countries FROM $tbl_name";
$result=mysqli_query($conn,$sql);
我想整合传输的prikey变量,以便我能够以下列方式查询数据库:
$sql="SELECT countries FROM $tbl_name where id=$prikey";
其中$ prikey是我存储从JavaScript文件中获取的值的地方。
我如何做到这一点?
答案 0 :(得分:2)
您需要将prikey
作为参数添加到GET网址。
<强>使用Javascript:强>
// The request is inside of a function so that each
// xmlhttp is a different object
function sendRequest(prikey) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState === 4)
{
if (xmlhttp.status === 200 || xmlhttp.status === 304)
{
myFunction(xmlhttp.responseText);
}
}
};
xmlhttp.open("GET", url + '?prikey=' + prikey, true);
xmlhttp.send();
}
// Send the requests
for(i = 0; i < 5; i++)
{
// Pass it the prikey
sendRequest(i + 1);
}
function myFunction(response)
{
// Do stuff
}
在您的PHP代码中,通过$ _GET数组获取它:
// Get the variable sent through the Ajax request
$prikey = $_GET['prikey'];
$conn = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
mysqli_select_db($conn,"$db_name")or die("cannot select DB");
$sql = "SELECT countries FROM $tbl_name WHERE id = $prikey";
$result = mysqli_query($conn,$sql);
// echo the result so that your JavaScript code gets the response
// Again, ignore if you've already done this
echo $result;