user2881809
user2881809

Reputation:

How to get value of each array element in JSON?

Here is my AJAX call:

$.ajax({
    url: "http://testsite.com/testurl.php",
    data: form,
    dataType: 'json',
    type: 'post',
    success: function(data) {
        console.log( 'success', data );
    },
    error: function() {
        console.log( 'error', arguments );
    }
});

In result we get this JSON:

{
   "answer" : {
      "domains" : [
         {
            "dname" : "ab.ru",
            "error_code" : "DOMAIN_EXISTS",
            "error_params" : {
               "dname" : "ab.ru",
               "servtype" : "domain"
            },
            "error_text" : "Domain exists",
            "result" : "error"
         },
         {
            "dname" : "ab.com",
            "error_code" : "DOMAIN_EXISTS",
            "error_params" : {
               "dname" : "ab.com",
               "servtype" : "domain"
            },
            "error_text" : "Domain exists",
            "result" : "error"
         },
         ...,
         {
            "dname" : "zz.com",
            "error_code" : "DOMAIN_EXISTS",
            "error_params" : {
               "dname" : "ab.com",
               "servtype" : "domain"
            },
            "error_text" : "Domain exists",
            "result" : "error"
         },
        "error_text" : "Domain already exists, use whois service",
        "result" : "error"
     }
      ]
   },
   "charset" : "utf-8",
   "result" : "success"
}

Tell me please how get each answer.domains[] ->dname and answer.domains[] ->error_code?

For example for first array it will be:

dname = ab.ru;
error_code = DOMAIN_EXISTS;

Upvotes: 0

Views: 52

Answers (1)

tymeJV
tymeJV

Reputation: 104775

Loop and and do your work:

for (var i = 0; i < data.answer.domains.length; i++) {
    var domain = data.answer.domains[i];

    //domain is the specific domain being iterated
    //domain.dname; -> zz.com
}

Upvotes: 2

Related Questions