簡體   English   中英

在Ajax jQuery中顯示JSON響應,

[英]Display json response in ajax jquery,

我得到的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

您必須在$ .ajax調用中設置dataType,將其設置為dataType:“ json” ...

之后,成功獲取json對象中的data變量,然后可以像data.user_data或data.id或data.first_name一樣訪問它。

如果您沒有將json定義為dataType,它將無法正常工作。

加成

如果要顯示“ question_with_answer”的內容,則必須迭代它,如...。

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

在成功處理程序中,首先使用以下命令將json放入數組

var obj = JSON.parse(data);

現在,在數據中您可以得到一系列的響應,您可以像這樣使用

obj.first_name

obj.last_name

注意:-可能是JSON.parse出現問題,請先使用

var data = json.stringify(data)

之后,使用Json.parse函數並使用上述數據變量將此數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM