I'm basically doing an Ajax call which returns a dynamic result each time, here's a sample of the response
[{"id":10858362988,"http_code":"200","result_code":"1"}]
How can I access the result_code
? I've tried doing the following to no avail
$.ajax({
type: "GET",
url: window.apiURL,
data: data,
success: function(data) {
var myObj = $.parseJSON(data);
switch(myObj.result.code) {
//this doesn't work for some reason???
}
}
});
Since the response of the AJAX GET
Request is an array, you have to access the key
using index
as suggested by @tymeJV.
$.ajax({
type: "GET",
url: window.apiURL,
data: data,
success: function(data) {
var myObj = $.parseJSON(data);
console.log(myObj[0]["result_code"]);
}
});
If the response is an array of objects:
Something like: [{"id":10858362988,"http_code":"200","result_code":"1"}, {"id":20858362988,"http_code":"404","result_code":"1"}]
, do something like below
$.ajax({
type: "GET",
url: window.apiURL,
data: data,
success: function(data) {
var myObj = $.parseJSON(data);
for (var i=0; i<myObj.length; i++) {
console.log(myObj[i]["result_code"]);
}
}
});
You would do:
var code = myObj[0]["result_code"];
You have an array containing 1 object, so reference the index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With