嘿我不经常使用PHP很可能一年一次,我有很多麻烦返回数据正确。基本上我得到一个对象,似乎包含我的数据在响应文本,我不知道为什么。如果有人能向我解释为什么会发生这种情况,我会非常感激!不正确地返回JSON数据
这是从后端
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);;
}
代码,这是前端代码
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]));
并且这是用PHP返回数据的行。我忘了添加它。
print_r(json_encode($ aResult));
抱歉,我使用的print_r返回 – Seamy
不要!而是使用'echo json_encode($ aResult);'[The manual](http://php.net/manual/en/function.json-encode.php) – RiggsFolly
什么是temp1?它是'数据'吗?如果不是数据中返回的内容? – LYu