我发出了一个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回应:[{&#34; id&#34;:&#34; 19&#34;,&#34; idlanguage&#34;:&#34; 1&#34;,&#34; name&# 34;:&#34; QI&#34;}&#34; OK&#34;]
但是我无法访问db行。
我搜索过并发现: Parse PHP array of objects with jQuery Ajax
但不理解答案,他们的例子只有1个字段。请帮忙。
答案 0 :(得分: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);
}
});