duanfu7840 2015-12-04 17:25
浏览 595
已采纳

JSON.parse(xmlhttp.responseText)返回空

I am using Ajax. My search.php contains the javascript code. It requests for content.php which echoes an array $res that contains values in the form of "key" : value.

content.php :

echo json_encode($res);

search.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>

However, when I print $res alone in a separate page, it shows the correct output which is:

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

I tried to loop through the array:

var array = JSON.parse(xmlhttp.responseText);

for(var index in array) {

 alert(index+ " is: "+ array[index]);
}

But this also doesn't alert anything. I've been trying and searching on this for days but couldn't find a working solution.

Edit:

here is the output of alert(xmlhttp.responseText) :

part 1 of the alert window

part 2 of the alert window

couldn't post more than two links (because I don't have enough reputation), anyway you had a glimpse of it, I believe.

  • 写回答

2条回答 默认 最新

  • dongting3135 2015-12-04 20:11
    关注

    According to what I can see in both images, your PHP is giving you HTML code after the JSON object, that could be the problem that stops you from parsing it. Make sure you end PHP execution after echoing $res. In other words, try with this line:

    echo json_encode($res);exit;
    

    Also, in case that doesn't work, please change alert(xmlhttp.responseText) to console.log(xmlhttp.responseText), check the browser console and copy here all the text you get back from the server

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献