从PHP中的while()循环获取数据时,AJAX失败 [英] AJAX fails while get data from while() loop in php
问题描述
当我使用json_encode($array)
时,我可以正确获取数据,但是当我在循环的数组中使用json_encode时,会收到以下错误消息
When I use json_encode($array)
I get the data properly but when I use json_encode within an array which is looped I Get the following error
[对象对象] parsererror语法错误:意外令牌{
[object Object] parsererror SyntaxError: Unexpected token {
我正在使用ajax从functions.php获取json数据
I'm using ajax to get json data from functions.php
$(function() {
$('#get').click(function(){
$.ajax({
url: 'http://android.ezinfotec.com/functions.php',
type : 'GET',
data : 'method=getquestions',
dataType : 'json',
success : function(s) {
console.log(s);
},
error: function(XMLHttpRequest,textStatus,errorThrown)
{
console.log(XMLHttpRequest+' '+textStatus+' '+errorThrown);
}
});
});
});
functions.php
The functions.php
<?php
header('Content-type: application/json');
include("connect.php");
if($_GET['method'] == 'getquestions')
{
$query = mysql_query("select * from questions");
while($fetch = mysql_fetch_array($query))
{
$output = array(
"id" => $fetch['id'],
"answers" => $fetch['answers'],
"status" => $fetch['ans_status'],
"postedon" => substr($fetch['month'],0,3).' '.$fetch['day'].' '.$fetch['year'],
"question" => $fetch['question'],
"category" => $fetch['category'],
"parent" => $fetch['parentcategory'],
"authorid" => $fetch['author'],
"authorname" => $fetch['author_name']
);
echo json_encode($output);
}
}
在上面的php代码中,如果我删除了while循环并为变量简单定义了自定义值,则我在html页面中获得了完美的数据.
In the above php code if I remove the while loop and simple define custom values to the variable i get perfect data in the html page.
注意:没有跨域问题,因为除了getquestions();
Note: There is no cross domain issue as I have many functions working except for getquestions();
您可以在 http://android.ezinfotec.com/functions中查看json输出.php?method = getquestions
推荐答案
您需要将所有记录追加到一个数组中,并对其进行json_encode编码.之所以失败,是因为将多个json对象发送回了预期只有一个的页面.
You'll want to append all of the records to one array and json_encode that instead. It is failing because multiple json objects are being sent back to the page where it expects only one.
$output = array();
while (...) {
$output[] = ...
}
// add a header too
header('Content-Type: application/json');
echo json_encode($output);
抱歉,这不是完整的代码.从我的手机上进行此操作很轻松.
这篇关于从PHP中的while()循环获取数据时,AJAX失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!