0

这是我在 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);

现在,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);
  }
})

有人可以帮我吗。在 JSON 中形成数组的正确方法是什么?

4

3 回答 3

1

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.

于 2013-06-18T21:11:56.683 回答
0

我会简化你的 jquery ......像这样......

$.getJSON("getDataForSlide.php", { limit: limit, required: required}, function(json) {
console.log(json);
});
于 2013-06-18T21:13:45.630 回答
0

我喜欢用

jQuery.parseJSON(response);

并且不要忘记使用 die(); 或退出();在你回显你的结果后,在 php 端,因为它是一个 ajax 调用。可以在此处找到此信息:http: //codex.wordpress.org/AJAX_in_Plugins

于 2013-06-18T21:18:33.623 回答