我正在尝试使用 Ajax 将 JSON 对象从 php 脚本传递到 Javascript 文件。下面的代码适用于一个简单的字符串,但我现在正试图对其进行修改以适用于 JSON 对象中包含的多个字符串。我在下面粘贴了每个文件的摘录。我做错了什么?
这是创建请求的 html/javascript 文件的摘录...
function retrieveAircraftInfo(str) {
var xmlhttp;
if (str.length==0) {
document.aircraftRegForm.aircraftManufacturer.value="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4) {
var aircraftDataJSON = xmlhttp.responseText.evalJSON();
document.aircraftRegForm.aircraftManufacturer.value = aircraftDataJSON.manufacuter;
document.aircraftRegForm.aircraftType.value = aircraftDataJSON.type;
document.aircraftRegForm.aircraftPopularName.value = aircraftDataJSON.popularName;
document.aircraftRegForm.aircraftGenericName.value = aircraftDataJSON.genericName;
}
}
xmlhttp.open("GET","scraper.php?q="+str,true);
xmlhttp.send();
}
这是执行数据库搜索的 php 文件的摘录:
$aircraftDataArray = array("manufacturer" => $extractedManufacturer,
"type" => $extractedType,
"popularName" => $extractedPopularName,
"genericName" => $extractedGenericName);
echo json_encode($aircraftDataArray);
最佳答案
尝试
var aircraftDataJSON = JSON.parse(xmlhttp.response);
否则,如果 PHP 返回一些错误,请检查开发人员工具的控制台。
你的 JS 示例使用 JSON.parse 对我有用
关于php - 通过 Ajax 将 JSON 对象从 php 传递到 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17121611/