简体   繁体   中英

HOW to Parse JSON response from the server after AJAX POST-request?

As you can see the problem from the title. Here is what I do:

send a request like

$.ajax({
  type: "POST",
  url: "http://www.example.com/api/",
  data: {
    'data': '1',
    'beacon': 'fried'
  },
  complete: function(res) {
    //need help here...
  }
});

The API does echo. If I do document.forms["myform"].submit(); page shows a JSON response like

{
  "data": [{
    "Chief": "Max",
    "temperature": "65",
    "done": "yes",
    "cost": 24
  }]
}

So how should I parse (check, display the values)? Tried many ways.

Any help would be appreciated !

PS using jquery-3.2.1.min.js

You could set the dataType to JSON in the request attribute :

 $.ajax({
    type: "POST",
    url: "http://www.example.com/api/",
    data: {'data': '1', 'beacon': 'fried'},
    dataType: 'JSON',
    complete: function (res) {
        console.log(res); // will be decoded
        // acces your values like this :
        var data = res.responceText.data[0];
        alert(data.Chief);
    }
 });

EDIT

Added how to access specific data.

you should use

JSON.parse()

As you have array in in json data , you can access it as res.data[0].cost or res.data[0]["cost"]

如果需要,请使用JSON.parse() ,否则您可以从res.data获取数组

Try JSON.parse()

$.ajax({
    type: "POST",
    url: "http://www.example.com/api/",
    data: {'data': '1', 'beacon': 'fried'},
    complete: function (res) {
       var arr = JSON.parse(res).data;

       arr.forEach(function(obj) {
           var cost = obj.cost || null,
                Chief = obj.Chief || null,
                temperature = obj.temperature || null,
                done = obj.done || null;

           console.log('Cost: ' + cost + ', Chief: ' + Chief + ', Temperature:' + temperature + ', Done: ' + done);
       });
    }
});

You could use JSON.parse()

 $.ajax({
        type: "POST",
        url: "http://www.example.com/api/",
        data: {'data': '1', 'beacon': 'fried'},
        complete: function (res) {
          var response = JSON.parse(res); 
        }
     });

Well the first problem was that it does not allow to response come out from different domain, so I transferred all the code to the same server where api is located.

Now this code works:

$.ajax({
  type: "POST",
  url: "../api/",
  data: {'data': '1', 'beacon': 'fried'},
  dataType: 'JSON',
  complete: function (res) {
  console.log(res);
  var r = JSON.parse(res.responseText);
  console.log(r.data[0].Chief); //retrieved Alex, that is response from the server
  }
});

Thanks all !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM