Parsing jQuery AJAX response

前端 未结 6 850
囚心锁ツ
囚心锁ツ 2020-12-06 09:29

I use the following function to post a form to via jQuery AJAX:

$(\'form#add_systemgoal .error\').remove();         


        
相关标签:
6条回答
  • 2020-12-06 09:53

    you must parse JSON string to become object

    var dataObject = jQuery.parseJSON(data);
    

    so you can call it like:

    success: function (data) {
        var dataObject = jQuery.parseJSON(data);
        if (dataObject.success == 1) {
           var insertedGoalId = dataObject.inserted.goal_id;
           ...
           ...
        }
    }
    
    0 讨论(0)
  • 2020-12-06 09:55

    calling

    var parsed_data = JSON.parse(data);
    

    should result in the ability to access the data like you want.

    console.log(parsed_data.success);
    

    should now show '1'

    0 讨论(0)
  • 2020-12-06 09:56

    Since you are using $.ajax, and not $.getJSON, your return type is plain text. you need to now convert data into a JSON object.

    you can either do this by changing your $.ajax to $.getJSON (which is a shorthand for $.ajax, only preconfigured to fetch json).

    Or you can parse the data string into JSON after you receive it, like so:

        success: function (data) {
             var obj = $.parseJSON(data);
             console.log(obj);
        },
    
    0 讨论(0)
  • 2020-12-06 10:18
     $.ajax({     
         type: "POST",
         url: '/admin/systemgoalssystemgoalupdate?format=html',
         data: formdata,
         success: function (data) {
             console.log(data);
         },
         dataType: "json"
     });
    
    0 讨论(0)
  • 2020-12-06 10:19

    Imagine that this is your Json response

    {"Visit":{"VisitId":8,"Description":"visit8"}}
    

    This is how you parse the response and access the values

        Ext.Ajax.request({
        headers: {
            'Content-Type': 'application/json'
        },
        url: 'api/fullvisit/getfullvisit/' + visitId,
        method: 'GET',
        dataType: 'json',
        success: function (response, request) {
            obj = JSON.parse(response.responseText);
            alert(obj.Visit.VisitId);
        }
    });
    

    This will alert the VisitId field

    0 讨论(0)
  • 2020-12-06 10:20

    Use parseJSON. Look at the doc

    var obj = $.parseJSON(data);
    

    Something like this:

    $.ajax({     
        type: "POST",
        url: '/admin/systemgoalssystemgoalupdate?format=html',
        data: formdata,
        success: function (data) {
    
            console.log($.parseJSON(data)); //will log Object
    
        }
    });
    
    0 讨论(0)
提交回复
热议问题