通过使用Ajax将数组从PHP传递到javascript获得错误的数组长度
我面临的问题是,当我使用Ajax将一个数组从一个PHP文件传递到另一个javascript文件时,我得到了正确的输入,但数组的长度是错误的。我不知道我做错了什么。这是我的两个文件和一些代码 Firstfile.php:通过使用Ajax将数组从PHP传递到javascript获得错误的数组长度,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我面临的问题是,当我使用Ajax将一个数组从一个PHP文件传递到另一个javascript文件时,我得到了正确的输入,但数组的长度是错误的。我不知道我做错了什么。这是我的两个文件和一些代码 Firstfile.php: function check() { xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if(xmlhttp.readyState==4 && xmlht
function check()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
graphData=xmlhttp.responseText;
alert(graphData);
// getting alert [["01_Mar_2016",38430],["02_Mar_2016",97183],["03_Mar_2016",107122]]
alert(graphData.length);
//getting alert 68 but it should be 3
}
else if(xmlhttp.status==404)
{
graphData="File not found";
}
}
xmlhttp.open("GET","SeocndFile.php",true);
xmlhttp.send();
}
SeocndFile.php
while($result = mysql_fetch_assoc($qryResult))
{
$data[] = array((string)$result['mimiDate'], (int)$result['sumMimi']);
}
print json_encode($data);
//print like this[["01_Mar_2016",38430],["02_Mar_2016",97183],["03_Mar_2016",107122]]
//which is correct.
responseText
是一个字符串。您需要使用JSON.parse()
为了安全起见,您应该将其包装在try/catch块中,或者如果您使用的是jQuery,则应转换为使用$.getJSON()
,并添加错误处理程序
$.getJSON('SeocndFile.php')
.done(graphData){
alert(graphData.length);
})
.fail(function(err){
console.log(err);
alert('Ooops...something went wrong');
});
responseText
是一个字符串。您需要使用JSON.parse()
为了安全起见,您应该将其包装在try/catch块中,或者如果您使用的是jQuery,则应转换为使用$.getJSON()
,并添加错误处理程序
$.getJSON('SeocndFile.php')
.done(graphData){
alert(graphData.length);
})
.fail(function(err){
console.log(err);
alert('Ooops...something went wrong');
});
它显示字符串的长度,因为responseText是字符串,所以length返回字符数 您需要首先将字符串解析为JSON:
alert(JSON.parse(xmlhttp.responseText).length);
它显示字符串的长度,因为responseText是字符串,所以length返回字符数 您需要首先将字符串解析为JSON:
alert(JSON.parse(xmlhttp.responseText).length);
如上所述,检查您正在接收的数据类型是否为字符串形式 强烈建议ajax调用使用Jquery,因为当响应是json时,可以以更方便的格式获取数据 使用jquery的代码示例如下:
$.get('SeocndFile.php').done(function(data)
{
//do stuff here when sucessfuly retrieve the data
})
.fail(function()
{
//Do stuff when 404 or 500
});
下面是关于如何使用它的文档:
此外,您还可以使用$.post()执行HTTP post操作。如上所述,检查您接收的数据类型是否为字符串形式 强烈建议ajax调用使用Jquery,因为当响应是json时,可以以更方便的格式获取数据 使用jquery的代码示例如下:
$.get('SeocndFile.php').done(function(data)
{
//do stuff here when sucessfuly retrieve the data
})
.fail(function()
{
//Do stuff when 404 or 500
});
下面是关于如何使用它的文档:
您还可以使用$.post()执行HTTP post操作。这不是因为它可能是字符串…它将始终是字符串不是因为它可能是字符串…它将始终是字符串