我的PHP脚本
<?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);
?>
我的javascript文件中的AJAX函数调用如下
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)
答案 0 :(得分:3)
我假设你想要返回数组中的元素数量。但是,count
不是正确的JavaScript属性。请改用temp.length
。
答案 1 :(得分:1)
这是正确的方法:
var obj = jQuery.parseJSON('["1","2"]');
alert(obj.length);
“。count”需要用“.length”代替。 在这里试试:http://jsfiddle.net/4rrYz/
答案 2 :(得分:1)
使用jQuery,您可以简化您的ajax调用btw:
function someFunction(){
$.ajax({
url: "mymethodpath",
type: 'get',
dataType: 'json',
success: function(jsonObj) {
alert(jsonObj.length);
}
});
}
您也可以使用$.getJSON()
,但我自己也喜欢使用基本功能(getJSON也会在幕后使用)。
答案 3 :(得分:0)
在浏览器窗口中调用您的php脚本,您将看到没有名为“count”的JSON对象。您的数组将包含标记为0,1,2,...
的元素如果您尝试显示temp [0],您应该会看到第一个值。