JSON.parse(xmlhttp.responseText) returns empty


JSON.parse(xmlhttp.responseText) returns empty

我正在使用Ajax。我的search.php包含javascript代码。它请求content.php,该回显包含 "key" : value 形式的值的数组$res

内容.php :

echo json_encode($res);

搜索.php:

 <!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"> </script>
 <script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText); //this alerts the correct content of $res but along with all the HTML page codes
var array = JSON.parse(xmlhttp.responseText); //also tried json_decode(xmlhttp.responseText, true); and jQuery.parseJSON( xmlhttp.responseText );
alert(array); // this doesn't alert at all
}
}
xmlhttp.open("GET", "<?php echo   @$this->config->base_url();  ?>index.php/content.php", true);
xmlhttp.send();
</script>

但是,当我在单独的页面中单独打印$res时,它会显示正确的输出,即:

{"1894":1,"1905":0,"1916":0,"1927":0,"1938":0,"1949":0,"1960":0,"1971":0,"1982":0,"1993":0,"2004":1,"2015":2}

我试图遍历数组:

var array = JSON.parse(xmlhttp.responseText);
for(var index in array) {
 alert(index+ " is: "+ array[index]);
}

但这也不会提醒任何事情。我已经尝试和搜索了几天,但找不到可行的解决方案。

编辑:

这是alert(xmlhttp.responseText)的输出:

警报窗口的第 1 部分

警报窗口的第 2 部分

不能发布超过两个链接(因为我没有足够的声誉(,无论如何你已经瞥见了它,我相信。

根据我在两张图片中看到的内容,您的 PHP 在 JSON 对象之后为您提供 HTML 代码,这可能是阻止您解析它的问题。确保在回显 $res 后结束 PHP 执行。换句话说,尝试使用以下行:

echo json_encode($res);exit;

另外,如果这不起作用,请将alert(xmlhttp.responseText)更改为 console.log(xmlhttp.responseText) ,检查浏览器控制台并在此处复制您从服务器返回的所有文本

<script type="text/javascript">
    var url=<?php echo "'" . $this->config->base_url() . 'index.php/content.php';?>;
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {/* this was unclosed */
        if( xmlhttp.readyState == 4 && xmlhttp.status == 200 ) {
            var r=xmlhttp.responseText;
            console.info('ajax response: %s ',r);
            var array = JSON.parse(r);
        }
    }
    xmlhttp.open( "GET", url, true );
    xmlhttp.send();
</script>