Ajax调用数据问题

时间:2014-07-16 18:54:39

标签: javascript jquery ajax

我有来自ajax调用的数据,如下所示:

[ { "id": "1", "name": "Jim", "age": "39", "address": "12 High Street, London", "hasCar": "1", "speaksForeignLanguage": "1", "canWorkNights": "1", "isStudent": "1" }, { "id": "2", "name": "Fred", "age": "29", "address": "13 High Street, London", "hasCar": "1", "speaksForeignLanguage": "1", "canWorkNights": "1", "isStudent": "0" }, { "id": "3", "name": "Bill", "age": "19", "address": "14 High Street, London", "hasCar": "1", "speaksForeignLanguage": "1", "canWorkNights": "0", "isStudent": "0" }, { "id": "4", "name": "Tom", "age": "39", "address": "15 High Street, London", "hasCar": "1", "speaksForeignLanguage": "0", "canWorkNights": "0", "isStudent": "0" }, { "id": "5", "name": "Cathy", "age": "29", "address": "16 High Street, London", "hasCar": "1", "speaksForeignLanguage": "0", "canWorkNights": "0", "isStudent": "1" }, { "id": "6", "name": "Petra", "age": "19", "address": "17 High Street, London", "hasCar": "1", "speaksForeignLanguage": "0", "canWorkNights": "1", "isStudent": "0" }, { "id": "7", "name": "Heide", "age": "39", "address": "18 High Street, London", "hasCar": "1", "speaksForeignLanguage": "1", "canWorkNights": "0", "isStudent": "0" }, { "id": "8", "name": "William", "age": "29", "address": "19 High Street, London", "hasCar": "1", "speaksForeignLanguage": "1", "canWorkNights": "0", "isStudent": "1" }, { "id": "9", "name": "Ted", "age": "19", "address": "20 High Street, London", "hasCar": "0", "speaksForeignLanguage": "0", "canWorkNights": "0", "isStudent": "1" }, { "id": "10", "name": "Mike", "age": "19", "address": "21 High Street, London", "hasCar": "1", "speaksForeignLanguage": "0", "canWorkNights": "0", "isStudent": "1" }, { "id": "11", "name": "Jo", "age": "19", "address": "22 High Street, London", "hasCar": "0", "speaksForeignLanguage": "1", "canWorkNights": "0", "isStudent": "1" } ]

我想对这些数据做些什么是绘制一个div元素,但我只想获得我想要绘制的具体数据信息。

function makeTable(data){
       var tbl_body = "";
          $.each(data, function() {
            $.each(this, function(k , v) {
                console.log(v.age);
              tbl_body += "<spam>"+v.age+"</spam>";      
            })
          })

        return tbl_body;
      }

但它表示未定义的v.age :(

这是我的ajax电话:

function updateEmployees(opts){
        $.ajax({
          type: "POST",
          url: "submit.php",
          dataType : 'json',
          cache: false,
          data: {filterOpts: opts},
          success: function(records){
            $('#listings').html(makeTable(records));
          }
        });
      }

在这个例子中,我怎么能得到年龄?

1 个答案:

答案 0 :(得分:2)

你正在使用两个函数..为什么会这样?你正在迭代对象属性..在这种情况下你不需要..试试这个:

function makeTable(data){
   var tbl_body = "";
      $.each(data, function() {
          console.log(this.age);
          tbl_body += "<span>"+this.age+"</span>";      
      })

    return tbl_body;
}

另请注意,我已将<spam>更改为<span> ..您写错了,我不知道您要做什么,但这不会产生任何表格。问你是否对此有所帮助。

相关问题