我正在使用 Ajax 将信息发送到服务器并返回 JSON 字符串。这是我正在使用的代码:
function getRequests(folder, mode) {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = singleBook(folder, mode);
xhr.open("GET", "bestreads.php?mode=" + mode + "&title=" + folder, true);
xhr.send(null);
}
function singleBook(folder, mode) {
alert(xhr.responseText);
if (mode == "info") {
var json = JSON.parse(xhr.responseText);
}
}
我已经测试了我的 PHP 脚本,并且 100% 确定它能够正确打印出每个可能的文件夹名称的正确 JSON 字符串。我已经验证了它创建的 JSON 字符串以确认这一点。 然而,这段代码使 xhr 完全为空。我尝试使用 xhr.stats 检查状态,但它返回 0,这对我来说没有意义,因为我认为它应该返回 404 或 200。
这是一个学校项目,我不允许使用 JQuery,所以我需要一个不使用它的解决方案。我在调用之前以同样的方式进行了 Ajax 调用,它的工作没有任何问题,但返回一个 XML 字符串而不是 JSON,这让我认为我需要执行其他操作来返回 JSON 字符串,但我不知道那是什么或许。
PHP 代码:
function createJson($folder) {
$path = "books/" . $folder . "/info.txt";
$infoFile = file($path);
$info = '{"title":"' . $infoFile[0] . '","author":"' . $infoFile[1] . '","stars":"' . $infoFile[2] . '"}';
print $info;
}
最佳答案
您需要将函数引用分配给 onreadystatechange
,而不是调用 singleBook
函数并将该函数返回的值分配给 onreadystatechange
.
还需要等待ajax请求后再处理
function getRequests(folder, mode) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = singleBook(xhr, folder, mode);
xhr.open("GET", "bestreads.php?mode=" + mode + "&title=" + folder, true);
xhr.send(null);
}
function singleBook(xhr, folder, mode) {
return function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
if (mode == "info") {
var json = JSON.parse(xhr.responseText);
}
}
}
}
关于javascript - Ajax调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41155335/