2017-07-29 170 views
2

JSON響應我得到,顯示JSON響應,

 { 
     "user_data": { 
     "id": 22, 
     "first_name": xxx, 
     "last_name": xxx, 
     "phone_number": "123456789", 
     }, 
     "question_with_answers" : [ 
      { 
      "id": 1, 
      "question_name": "Features of our project that you like (select one 
      or more):", 
      "answers": [ 
       { 
       "id": 19, 
       "question_id": 1, 
       "customer_id": 22, 
       "option": "Location", 
       }, 
       { 
       "id": 20, 
       "question_id": 1, 
       "customer_id": 22, 
       "option": "Architecture", 
       }, 
       ] 
      }, 
      { 
      "id": 2, 
      "question_name": "Features of our project that you DID NOT like 
      (select one or more):", 
       "answers": [ 
       { 
       "id": 22, 
       "question_id": 2, 
       "customer_id": 22, 
       "option": "Location", 
       }, 

       ] 
      }, 
      { 
      "id": 3, 
      "question_name": "How soon are you looking to buy a new home?", 
      "answers": [ 
        { 
         "id": 24, 
         "question_id": 3, 
         "customer_id": 22, 
         "option": "Immediately", 
        } 
       ] 
       } 
      ] 
      } 

所以這是JSON響應的樣子,現在我需要使用jQuery

我的js代碼

顯示數據
 function openModal(Id){ 
    var CustomerId = Id; 
    $.ajax({ 
     type : 'get', 
     url: 'customer-details', 
     data: { 
      'CustomerId':CustomerId 
     }, 

     success: function(data) 
     { 
      //what I have to do here 
     } 
    }) 
} 

我要的是輸出,

first_name : xxx   
last_name : xxx 
phone_number : 123456789 

1.Features of our project that you like (select one or more): 
ans: Location, Architecture 

2.Features of our project that you DID NOT like (select one or more) 
ans: Location 

3.How soon are you looking to buy a new home? 
ans: Immediately 

那是我的輸出如何看起來像從上面的JSON響應,是否有可能使用JSON響應我 有跡象表明,我已經從後端方式通USER_DATA和question_with_answers兩個可變

+0

你可以添加HTML元素使用JavaScript或jQuery的頁面? – marzelin

+1

是的,我可以@marzelin – manjunath

回答

1

你必須設置以獲得上述輸出在$ .ajax調用dataType,將其設置爲dataType:「json」... ...

之後,你在成功的數據變量json對象,你可以像data.user_data或數據訪問它.id或data.first_name。

如果你不把json定義爲dataType,它將無法正常工作。

加成

如果你想顯示的「question_with_answer」的內容,你必須遍歷槽它,就像....

for (i in data.question_with_answer) { alert(data.qestion_with_answer[i]); }

+0

hello,@rebru我可以顯示第一個對象user_data,但是它裏面有一個數組,我感到困惑。 – manjunath

+1

如何顯示question_with_answers數組值 – manjunath

+0

我編輯過我的第一篇文章,對於需要迭代的對象中的數組。 – rebru

1

在成功處理程序首先要把你的JSON到使用

var obj = JSON.parse(data);

現在的數據你有你的反應和y的陣列陣列您可以同時使用這像

obj.first_name

obj.last_name

注: - 可能是你有問題JSON.parse所以用第一

var data = json.stringify(data)

在使用Json.parse功能,使用後上面的數據變量 這個數據

+0

什麼第二可變數據有兩個可變的請看看 – manjunath

+0

var data = JSON.parse(data);這裏的數據是你從PHP獲得的json,並傳遞給成功處理程序,並給出一些時間給出錯誤,因爲json在字符串中轉換是的我知道josn是一個字符串,但json有一個特定的格式,所以如果你面對錯誤,它會給出錯誤,在json之前var data = json.stringify(data)'。解析函數並在stringify函數中傳遞你在成功處理器中使用的json 可能你有我的觀點兩個數據都是一樣的 –

+0

我認爲obj.user_data.first_name在解析後會工作。 – falero80s