我正在尝试对一个非常小的PHP脚本进行AJAX调用,该脚本应该返回一个可以使用JQuery进行回声和解码的数组。这就是我所拥有的:
我的PHP页面由AJAX调用:
$web_q=mysql_query("select * from sec_u_g where uid='$id' ");
$rs = array();
while($rs[] = mysql_fetch_assoc($web_q)) {
}
print_r(json_encode($rs));
输出:
[{"id":"3","uid":"39","gid":"16"},{"id":"4","uid":"39","gid":"4"},{"id":"5","uid":"39","gid":"5"},{"id":"6","uid":"39","gid":"6"},{"id":"7","uid":"39","gid":"7"},{"id":"8","uid":"39","gid":"8"},{"id":"9","uid":"39","gid":"9"},false]
我不明白最后的一个“假”..然后我发送给JQuery并使用:
$.each(json.result, function(i, object) {
$.each(object, function(property, value) {
alert(property + "=" + value);
});
});
这只是失败了。我尝试通过以下方式提醒“结果”:
$.post("get_ug.php",{id:txt},function(result){
});
我的输出提醒如下:
1) The key is '0' and the value is '['
2) The key is '1' and the value is 'f'
3) The key is '2' and the value is 'a'
4) The key is '3' and the value is 'l'
5) The key is '4' and the value is 's'
6) The key is '5' and the value is 'e'
7) The key is '6' and the value is ']'
8) The key is '7' and the value is '
' (<-- Yes the line break is there in the alert)
我厌倦了尝试不同的想法和脚本。除了自己设置分隔符并连接我自己的数组并使用自定义脚本解码之外,有没有人有任何想法?谢谢!!
答案 0 :(得分:0)
false
来自你的while循环:
while($rs[] = mysql_fetch_assoc($web_q))
在最后一次迭代中,mysql_fetch_assoc
返回false,插入$ rs [],从而找到json的方式。
这也是导致你的json无效的原因
通过使用循环的临时变量来摆脱这个false
之后一切都会好起来的。
编辑(带有临时变量的修改代码):
$web_q=mysql_query("select * from sec_u_g where uid='$id' ");
$rs = array();
$result; //temporary variable to hold the current 'fetch' result.
while($result = mysql_fetch_assoc($web_q)) {
array_push($rs, $result); //push the result into the array only if it
//passed the loop condition.
}
print_r(json_encode($rs));
注意:强>
您可以使用array_push($rs, $result);
来代替$rs[] = $result;
。
编辑2(jQuery + json):
为了解析json对象,这里是一个如何构建ajax调用的例子:
$.ajax({
url: "get_ug.php",
data: {
id: txt
},
type: "POST",
dataType: "json", //important (!!) - this makes sure the received data is parsed as json.
success: function(data){
//'data' is the resulting json object which is received from your php file.
//use it to access your data.
console.log( data );
}
});
答案 1 :(得分:0)
为什么要使用print_r打印结果?它不再是递归对象,因此print
或echo
就足够了。