[英]Not returning JSON data correctly
Hey I don't use PHP very often maybe once a year and I am having a lot of trouble returning data correctly. 嘿,我可能每年不经常使用PHP,并且正确返回数据时遇到很多麻烦。 Basically I am getting an object that seems to contain my data in the response text which I don't know why.
基本上,我得到的对象似乎在响应文本中包含我的数据,但我不知道为什么。 If someone could explain to me why this happens I'd be very grateful!
如果有人可以向我解释为什么会发生这种情况,我将不胜感激!
this is the code from the back end 这是来自后端的代码
if(isset($_POST['action']) && !empty($_POST['action'])) {
switch ($_POST['action']){
case'getCandidates' :
{
$bus = array(
'latitude' => $row['lat'],
'longitude' => $row['lng'],
'icon' => './images/' . $row['busColor'] . '.png'
);
array_push($json, $bus);
$query = "SELECT * from candidates WHERE status = '$status' AND category = '$category' AND location = '$location'";
$returnRows = $db->con->query($query);
if ($returnRows->num_rows > 0) {
$x = 0;
// output data of each row
while($row = $returnRows->fetch_assoc()) {
$object = new stdClass();
$object->status = $row["status"];
$object->first_name = $row["first_name"];
$object->last_name = $row["last_name"];
$object->category = $row["category"];
array_push($aResult, $object);
}
} else {
$aResult[0] = "No results";
}
// $aResult['result'] = mysql_fetch_object($returnRows);;
}
and this is the front end code 这是前端代码
returnedCandidates = $.ajax({
url: "../php/admin.php",
type: 'POST',
dataType: 'json',
data: {action: 'getCandidates'},
success: function(data, textStatus, jqXHR) {
alert(data);
}});
console.log(JSON.parse(returnedCandidates[0]));
and this is the line for returning data with php. 这是用php返回数据的行。 I forgot to add it.
我忘了加。
print_r(json_encode ($aResult)); print_r(json_encode($ aResult));
comment line: 评论行:
//print_r(json_encode ($aResult));
and return like this: 然后像这样返回:
return (json_encode ($aResult));
Don't use print_r for return. 不要使用print_r返回。
Try this code: 试试这个代码:
header('Content-Type: application/json');
echo json_encode($aResult);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.