我面临的问题是,当我使用 Ajax 将数组从 PHP 文件传递到另一个文件 javascript 时,我得到正确的输入,但数组的长度是错误的。我不知道我做错了什么。这是我的两个文件的一些代码。
Firstfile.php:
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();
}
SecondFile.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()
var graphData=JSON.parse(xmlhttp.responseText);
为了安全起见,您应该将其包装在 try/catch block 中,或者如果您使用的是 jQuery,则转换为使用 $.getJSON()
并添加错误处理程序
$.getJSON('SeocndFile.php')
.done(graphData){
alert(graphData.length);
})
.fail(function(err){
console.log(err);
alert('Ooops...something went wrong');
});
关于javascript - 使用 Ajax 将数组从 PHP 传递到 javascript 获取错误的数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35817486/