我正在尝试使用json_encode,以便我的jquery ajax函数可以从我的php脚本中检索数据,但是我尝试编码和检索的数组是一个对象数组
$la_uselessinfo = array();
$lv_cnt = 0;
$uselessinfo = pg_execute($gv_dbconn, "uselessinfo_cur", array());
while($la_row = pg_fetch_row($uselessinfo)) {
$la_uselessinfo[$lv_cnt]["uinf_idno"] = $la_row[0];
$la_uselessinfo[$lv_cnt]["uinf_desc"] = $la_row[1];
$lv_cnt = $lv_cnt + 1;
}
echo json_encode($la_uselessinfo);
我正在尝试使用jquery ajax函数
来检索它$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
success : function(data) {
//console.log(data);
console.log(data["uinf_desc"][0]);
},
error : function(log) {
console.log(log.message);
}
});
我收到以下错误
Uncaught TypeError: Cannot read property '0' of undefined
我无法判断php代码或jquery代码是否出错,检索对象数组的正确方法是什么?
答案 0 :(得分:1)
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
dataType: "json",
success : function(data) {
console.log(data[0]["uinf_desc"]);
console.log(data[0]["uinf_desc"]);
},
应该是data[0]["uinf_desc"]
,如PHP中所写
答案 1 :(得分:1)
将您的PHP更改为:
$la_uselessinfo = array();
$lv_cnt = 0;
$uselessinfo = pg_execute($gv_dbconn, "uselessinfo_cur", array());
while($la_row = pg_fetch_row($uselessinfo)) {
$la_uselessinfo[$lv_cnt]["uinf_idno"] = $la_row[0];
$la_uselessinfo[$lv_cnt]["uinf_desc"] = $la_row[1];
$lv_cnt = $lv_cnt + 1;
}
echo json_encode($la_uselessinfo); //$la_uselessinfo is already an array, no need to wrap it again, and doing so causes you to misjudge the depth of your array
然后将您的jQuery更改为:
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
success : function(data) {
//console.log(data);
console.log(data[0]["uinf_desc"]); // this line changed
},
error : function(log) {
console.log(log.message);
}
});
要循环结果,请执行以下操作:
// sample data
var data = [{
"uinf_idno": "1",
"uinf_desc": "website db "
}, {
"uinf_idno": "2",
"uinf_desc": "local apache "
}]
$.each(data,function(i,e){
var uinf_idno = e.uinf_idno;
var uinf_desc = e.uinf_desc;
$('#result').append('uinf_idno= '+uinf_idno+' and uinf_desc= '+uinf_desc+' <br>');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
&#13;