javascript - 如何在AJAX中输出Json数据

标签 javascript json ajax

在原生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/

相关文章:

json - Powershell - JSON 文件到表

java - 使用java servlet的异步文件上传

javascript - JSON 访问数据 - 奇怪的行为

javascript - 在Javascript中获取JSON的内部数组值

javascript - 我需要向 Google map api 添加许多标记,并使用 Prompt() 添加注释

python - 在Python中循环处理后移动文件的权限错误

jquery - 延迟 ajaxStart n 秒

javascript - 如何使用 jQuery 设置 externalHTML

javascript - 如何将静态古腾堡 block 转换为动态 block 并使用 PHP 注册它?

javascript - Magnific-Popup 关闭回调不执行