如何在JSON中获取每个数组元素的值?

时间:2014-12-29 14:08:09

标签: jquery arrays json

这是我的AJAX电话:

$.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 );
    }
});

结果我们得到了这个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"
}

请告诉我如何获取每个answer.domains[] ->dnameanswer.domains[] ->error_code

例如,对于第一个数组,它将是:

dname = ab.ru;
error_code = DOMAIN_EXISTS;

1 个答案:

答案 0 :(得分:2)

循环并完成你的工作:

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
}