我发出 AJAX 请求:
function getdbsite(wantedid) {
alert(wantedid);
$.ajax({
url: 'public/xml/xml_getdbsite.php',
dataType: 'text',
data: {"wantedid": wantedid},
type: 'POST',
success: function (data) {
resultObj = eval(data);
site=resultObj[0];
// alert(site->language); }These cause errors
// alert(site->name); }
reply=resultObj[1];
}
});
}
服务器端 PHP:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once '../../includes/initialize.php';
header("Content-Type: application/json");
$id=$_POST['wantedid'];
$site = Website::find_by_id($id);
if($site){
$arr[0] = $site;
$arr[1] = "OK";
}else {
$arr[0] = "$id";
$arr[1] = "Failed";
}
$arr = json_encode($arr);
echo("$arr");
AJAX 响应:[{"id":"19","idlanguage":"1","name":"QI"},"OK"]
但我无法访问数据库行。
我搜索了一下,发现: Parse PHP array of objects with jQuery Ajax
但不明白答案,他们的例子只有 1 个字段。请帮忙。
最佳答案
我强烈建议不要使用 eval()
函数。
相反,明确设置您将从服务器接收 JSON:
dataType: 'JSON',
示例:
PHP:
if($site){
$arr['data'] = $site;
$arr['message'] = "OK";
}else {
$arr['data'] = $id;
$arr['message'] = "Failed";
}
echo json_encode($arr);
exit;
JS:
$.ajax({
url: 'public/xml/xml_getdbsite.php',
dataType: 'JSON',
data: {"wantedid": wantedid},
type: 'POST',
success: function(response) {
// use dot notation not -> arrow notation
var data = response.data;
var message = response.message;
alert(message);
alert(data.id);
alert(data.idlanguage);
}
});
关于javascript - 如何访问ajax调用返回的对象中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26331352/