2013-02-09 31 views
0

我正在使用codeigniter框架来开发我的网站。目前,我使用jQuery发送一个AJAX请求以从服务器获取数据。我试过两种方法,一种是数据在PHP关联数组中,另一种是在JSON对象中。请看到我从AJAX请求返回的数据:如何在codeigniter中获取json对象的值

{ 
    "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]); 

但出现的错误是:

Uncaught TypeError: Cannot read property '0' of undefined

任何人都可以给我一些关于如何获取值或将对象存储在数组中的建议。

+0

你可以发布让服务器发出ajax请求的jQuery代码吗? – james246 2013-02-09 17:10:03

回答

0
header("content-type:application/json"); 
对象的值
  • 是由服务器发送你的json?

下一个检查:


  • 使用$ .getJSON或$就与datatype='json'

最后, 然后访问你的对象data.o['0'].q_id

+0

如果我写在我的网页标题从哪里获得的页面显示I M使用CodeIgniter的框架HTML中的数据仍然没有工作。我试试data.o ['0']。q_id和data.o ['0'] ['q_id']。但仍然无法正常工作,我可以在视图文件或控制器中添加标题? – Rizwan 2013-02-10 07:32:23

+0

感谢mikakun现在的工作我只添加dataType:'json'在ajax函数中现在我得到我的数据在对象形式非常感谢你 – Rizwan 2013-02-10 07:50:36

2

因为这里Ø为对象的广告不是array..use .

试试这个

alert(data.o[0]) 

使用循环$.each功能进去o

data.o[0].each(function(i,v){ 
    console.log(v.q_id); 
}); 
+0

这是我调用ajax请求的函数,它返回问题中显示的数据。我尝试alert(data.o [0]);但仍然得到相同的错误。(){ public function getQuestions(){ \t \t \t $ this-> includeDB(); \t \t \t \t \t \t $ qId = $ this-> input-> POST('id'); \t \t \t \t \t \t $ array = $ this-> userDBclass-> getQuestions($ qId); \t \t \t $ data ['o'] = $ array; \t \t \t echo json_encode($ data); \t \t} \t} – Rizwan 2013-02-09 20:02:34

+0

感谢bipen你的快速答复我的问题,现在解决了 – Rizwan 2013-02-10 07:51:25

1

尝试使用标准对象捕捉JSON发送到你的JavaScript代码

我的代码,如:

VAR模型=新StdObject(); model-> blabla =“something”;

返回模型;