2017-07-29 177 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