dongnue4923 2013-06-18 21:07
浏览 106
已采纳

无法将PHP数组传递给jquery:JSON数据后出现意外的非空白字符

Here is what I have in PHP:

$arrayresults = array();
while($popularbrushesrow = mysql_fetch_array($popularBrushes)){

$arrayresults[]  = '<a href="brushdescription.php?id='.$popularbrushesrow['bd_brushid'].'"><img class="slideImg" alt="'.$popularbrushesrow['bd_brushname'].'" title="'. $popularbrushesrow['bd_brushname'].'" src="'.$popularbrushesrow['bd_imagefilepath'].'"  /></a>';

}

echo json_encode($arrayresults);

Now, jquery:

$.ajax({
    type:'GET',
    url:'getDataForSlide.php',
    data:"limit="+limit+"&required="+required,
    dataType:"json",
    cache:true,
        success: function(result){
     var arrayFromPHP = JSON.parse(result);
     alert(arrayFromPHP);
  }
})

Could someone please help me out. Whats the correct way to form an array in JSON?

  • 写回答

3条回答 默认 最新

  • duanping1632 2013-06-18 21:11
    关注

    The problem is likely to be this line:

    var arrayFromPHP = JSON.parse(result);
    

    Because you've specified dataType: 'json' in the ajax options, jQuery has already done the parsing for you. So doing it a second time starts out by doing toString on the array, which does a join, which results in invalid JSON.

    Simply use result directly.

    For example, suppose you have this JSON:

    [
        "<a href=\"http://stackoverflow.com\">Stack Overflow</a>",
        "<a href=\"http://google.com\">Google</a>"
    ]
    

    Because jQuery has already done JSON.parse on it, result is an actual array. So if you then pass it into JSON.parse, the first thing that does is toString, which gives you this:

    <a href="http://stackoverflow.com">Stack Overflow</a>,<a href="http://google.com">Google</a>
    

    ...which is not, of course, valid JSON.

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

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用