我正在通过以下请求从我的data.php
文件中请求数据:
xmlhttp.send('request=getchartdata&'+'chart='+chart+'&'+'key='+key);
这是
data.php
的内容:if ($_POST["request"] == "getchartdata") {
/*Removing dash from key*/
$key = str_replace("-", "", $_POST["key"]);
if ($_POST["chart"] == "associationEvolutionSubventions") {
$result = $conn->prepare("SELECT grantYear, grantAmount FROM granttoassociation WHERE HEX(grantReceiver) = ? ");
/*grantReceiver is in binary*/
}
$result->execute(["{$key}"]);
while($rs = $result->fetch()) {
if ($outp != "") {
array_push($outp,$rs);
}
}
}
$outp = json_encode($outp);
echo($outp);
但是,我在
xmlhttp.responseText
中得到一个空数组。与MySQL数据库的连接不是问题(另一个xmlhtpp请求正确返回了数据)。不过,有一点我不确定我的代码:
$result->execute(["{$key}"]);
语法在这里正确吗?HEX(grantReceiver)
给定grantReceiver为二进制,这样做是否正确?$key = str_replace("-", "", $_POST["key"]);
是删除破折号的正确语法吗?编辑:这是要求的完整AJAX代码。
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("POST", "wp-content/plugins/mygaloochart/data.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('request=getchartdata&'+'chart='+chart+'&'+'key='+key);
最佳答案
重新排列您的代码。打开请求并设置请求标头后,您应该侦听onreadystate(以下是您的修改后的代码):
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "wp-content/plugins/mygaloochart/data.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.send('request=getchartdata&'+'chart='+chart+'&'+'key='+key);