处理由PHP为AJAX调用javascript中
我的PHP脚本处理由PHP为AJAX调用javascript中
<?php
//connect to server
//selecting the database
$temparr=array();
$count=0
$result = mysql_query("some query");
while($row = mysql_fetch_assoc($result))
{
$temparr["$count"]= $row["value"] ;
$count+=1;
}
echo json_encode($temparr);
mysql_close($conn);
?>
的AJAX的函数调用在我的javascript文件返回的数据是那么,如何解析字符串如下
function someFunction(){
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "mymethodpath", true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
//this gives me a popup of the encoded data returned by the php script
// the format i see in the popup window is ["1","2"]
var temp=$.parseJSON(xmlhttp.responseText);
alert(temp.count);
//however this produces an undefined value
}
xmlhttp.send();
}
返回并显示正确的计数(这里计数应该是2)
我假设你想要返回数组中的元素数。但是,count
不是正确的JavaScript属性。改为使用temp.length
。
非常感谢你! – 2013-03-11 12:03:07
在浏览器窗口中调用您的php脚本,您将看到您没有名为“count”的JSON对象。您的阵列将包含标记为0,1,2 ...
的元素如果您尝试显示temp [0],则应该看到您的第一个值。
下面是正确的方法:
var obj = jQuery.parseJSON('["1","2"]');
alert(obj.length);
“.Count之间的” 需要通过 “长度” 来代替。这里 尝试:http://jsfiddle.net/4rrYz/
非常感谢! – 2013-03-11 12:04:03
不客气!你能把这个标记为答案吗? – unicorn80 2013-03-11 12:04:39
使用jQuery,您可以顺便说一句简化Ajax调用:
function someFunction(){
$.ajax({
url: "mymethodpath",
type: 'get',
dataType: 'json',
success: function(jsonObj) {
alert(jsonObj.length);
}
});
}
你也可以使用$.getJSON()
但我自己想留在基本功能(其中的getJSON会过于使用背后场景)。
谢谢!我相对较新的jQuery,所以会读你的调整! – 2013-03-11 12:08:57
我在PHP脚本的while循环中填充$ temparr。 – 2013-03-11 11:54:24
请注意,不建议使用'mysql_ *'函数(请参见[red box](http://php.net/mysql_query))。顺便说一句,如果你使用jQuery,为什么不使用['$ .getJSON'](http://api.jquery.com/jQuery.getJSON/)? – 2013-03-11 11:55:21
使用obj = JSON.parse(xmlhttp.responseText);也可以考虑在$ temparr [“$ count”]键中删除$ ... – 2013-03-11 11:56:16