在原生JS中,我只知道如何使用AJAX从PHP/mySql输出结果,而不是Json编码到元素“some_id”,如下所示:
<script>
function addItem(value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("some_id").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","some_php.php?q="+value,true);
xmlhttp.send();
}
</script>
但是如果PHP/mySQL的结果是Json Encoded,我如何在AJAX中将其输出到“some_id”?
最佳答案
首先用 JSON.parse()
解析 json :
如果您的回复如下所示:
{
"response": "This is a test response"
}
使用类似的东西:
<script>
function addItem(value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//Convert from a string to a javascript object
var json = JSON.parse(xmlhttp.responseText);
document.getElementById("some_id").innerHTML = json.response;
}
}
xmlhttp.open("GET","some_php.php?q="+value,true);
xmlhttp.send();
}
</script>
关于javascript - 如何在AJAX中输出Json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44490881/