[英]How can I return an array object to a jquery $.ajax call?
I am trying to return an array object to my Jquery ajax call, but it seems to return as a String with Array length =1 我正在尝试将数组对象返回给我的Jquery ajax调用,但是它似乎以Array length = 1的String形式返回
PHP code: PHP代码:
$results = mysqli_query($link, $sql);
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$array = array($row['eventDate'], $row['time'] ,['data' => $row['time']]) ;
echo json_encode($array) ;
}
} else {
echo "0 results";
}
Response in Developer tools shows: 开发人员工具中的响应显示:
["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}]["12_03_2015","0:00:00",{"data":"0:00:00"}]
My Ajax Call: 我的Ajax电话:
function trend(data){ 功能趋势(数据){
$.ajax({
url: "trendData.php",
cache: true,
type: "POST",
data: {arr:data},
success: function (data) {
originalData=[];
originalData.push(data)
trender(data)
}
});
} }
In the Preview window for Network, it shows an Array: 在“网络”的“预览”窗口中,它显示一个数组:
I cannot get an array of , in this example, 3 objects and get the array.length of 3 我在这个例子中无法获得3个对象的数组,而无法获得3的array.length
Any help will be much appreciated. 任何帮助都感激不尽。
You should collect all your data and return it as one json result and add a correct http-header (suggested by @Flosculus) so that the json format will be recognized: 您应该收集所有数据并将其作为一个json结果返回,并添加正确的http标头(由@Flosculus建议),以便可以识别json格式:
$results = mysqli_query($link, $sql);
$data = array();
if ($results->num_rows > 0) {
while ($row = $results->fetch_assoc()) {
$data[] = array($row['eventDate'], $row['time'] ,['data' => $row['time']]) ;
}
header('Content-Type: application/json');
echo json_encode($data) ;
} else {
echo "0 results";
}
I think you have to use JSON.parse() , if you're using jquery so your js script will look like 我认为您必须使用JSON.parse() ,如果您使用的是jquery,那么您的js脚本将类似于
$.ajax({
url: "trendData.php",
cache: true,
type: "POST",
data: {arr:data},
success: function (data) {
var data = JSON.parse(data);
//see length of array
console.log(data.length);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.