2013-02-09 29 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」;

返回模型;