我正在使用codeigniter框架来开发我的网站。目前我正在使用jQuery发送一个AJAX请求来从服务器获取数据。我尝试了两种方法,一种是数据在PHP关联数组中,另一种是在JSON对象中。请查看我从AJAX请求返回的数据:
{
"o": [
{
"q_id": "83",
"t_id": "4",
"question": "jjjjs.jfdaskldjf",
"option1": "jjjjasdfasdf",
"option2": "jjj",
"option3": "lll",
"option4": "lll",
"answer": "lll",
"marks": "22"
},
{
"q_id": "84",
"t_id": "4",
"question": "This is testing",
"option1": "2",
"option2": "7",
"option3": "8",
"option4": "9",
"answer": "2",
"marks": "2"
},
{
"q_id": "85",
"t_id": "4",
"question": "hello this is another test",
"option1": "a",
"option2": "b",
"option3": "c",
"option4": "d",
"answer": "a",
"marks": "2"
},
{
"q_id": "86",
"t_id": "4",
"question": "another test",
"option1": "8",
"option2": "9",
"option3": "0",
"option4": "1",
"answer": "1",
"marks": "2"
},
{
"q_id": "87",
"t_id": "4",
"question": "last question ",
"option1": "z",
"option2": "x",
"option3": "c",
"option4": "v",
"answer": "c",
"marks": "2"
}
]
}
我正在访问它:
alert(data["o"][0]);
但发生的错误是:
未捕获的TypeError:无法读取未定义的属性“0”
任何人都可以给我一些关于如何获取值或将对象存储在数组中的建议。
答案 0 :(得分:2)
因为这里的对象广告不是数组..使用.
试试这个
alert(data.o[0])
使用循环$.each
函数获取o
data.o[0].each(function(i,v){
console.log(v.q_id);
});
答案 1 :(得分:1)
尝试使用Std Object捕获将JSON发送到您的javascript代码
我的代码如下:
var model = new StdObject(); model-> blabla =“something”;
返回模型;
答案 2 :(得分:0)
header("content-type:application/json");
下一次检查:
datatype='json'
最后,
然后访问您的对象data.o['0'].q_id