如何从json文件中获取每个值

时间:2016-08-05 14:54:18

标签: javascript json datatables cakephp-2.6

我尝试将数据发送到json文件中的数据表,如下: 例如我的json文件的数据:

"responseHeader":{
    "status":0,
    "QTime":2,
    "params":{
      "q":"vba",
      "indent":"true",
      "fl":"name,role_t,born,natio_t",
      "wt":"json"}},
  "response":{"numFound":7,"start":0,"docs":[
      {
        "name":"Khouli",
        "born":["1978-04-03T00:00:00Z"],
        "natio_t":"tunisien",
        "role_t":"Consultant"},
      {
        "name":"Atayi",
        "born":["1987-06-24T00:00:00Z"],
        "natio_t":"Francaise",
        "role_t":"Consultant"}
}

这是我的功能:

$ ( document ).ready(function() {
$.ajax({
    type: 'GET',
    url: '../search.json',
    success: function(data) {
        $.each(data, function(i, data) {
            var body = "<tr>";
            body    += "<td>" + data.name + "</td>";
            body    += "<td>" + data.born + "</td>";
            body    += "<td>" + data.natio_t + "</td>";
            body    += "<td>" + data.role_t + "</td>";

            body    += "</tr>";
            $('.datatable-ajax-source table').append(body);
        });

但是我得到了具有未定义价值的表格 this is my table result

如何从json文件中获取此值

2 个答案:

答案 0 :(得分:0)

您的输入数据似乎有误:此处更正了数据:

{
"responseHeader":{
    "status":0,
    "QTime":2,
    "params":{
      "q":"vba",
      "indent":"true",
      "fl":"name,role_t,born,natio_t",
      "wt":"json"}},
      "response":{"numFound":7,"start":0,"docs":[
      {
        "name":"Khouli",
        "born":["1978-04-03T00:00:00Z"],
        "natio_t":"tunisien",
        "role_t":"Consultant"},
      {
        "name":"Atayi",
        "born":["1987-06-24T00:00:00Z"],
        "natio_t":"Francaise",
        "role_t":"Consultant"}
     ]
}
}

正确的JS来处理这个问题:

$(document).ready(function() {
$.ajax({
type: 'GET',
url: '../search.json',
success: function(data) {
    // Data is the root node of your json response.
    // You need to navigate through the "docs" node.
    if(data.response.docs && data.response.docs.length > 0)
    {
    $.each(data.response.docs, function(i, item) {
        var body = "<tr>";

        body    += "<td>" + item.name + "</td>";
        body    += "<td>" + item.born + "</td>";
        body    += "<td>" + item.natio_t + "</td>";
        body    += "<td>" + item.role_t + "</td>";

        body    += "</tr>";
        $('.datatable-ajax-source table').append(body);
    }
    });

您没有获得data的正确值。 您应该获得docs.data[i],在这种情况下,item定义.each()

答案 1 :(得分:-2)

你没告诉jquery你期待json回来,所以它接受了服务器响应中的JSON字符串作为明文,并将其作为纯文本传递给data

使用.getJSON(),它会将响应自动解析为本机JS数据结构,或者

$.ajax(
  ...
   dataType: "json"
  ...
);