调试jQuery AJAX响应:我做错了什么?

时间:2009-11-08 12:36:39

标签: javascript jquery ajax debugging json

$.ajax({
    type: 'POST',
    url: 'place/add',
    data: {
        lat: lat,
        lng: lng,
        name: name,
        address: address,
        phone: phone,
        review: review,
        category: category
    },
    success: function(data) {
    alert(data);
    alert(data.id);
    // ......
});

第一个提醒:{"id":"2","success":true},但第二个提醒:undefined

3 个答案:

答案 0 :(得分:11)

您需要将预期的返回数据类型指定为JSON:

$.ajax({
    type: 'POST',
    dataType: 'json', // specifies the return type
    url: 'place/add',
    data: {
        lat: lat,
        lng: lng,
        name: name,
        address: address,
        phone: phone,
        review: review,
        category: category
    },
    success: function(data) {
        alert(data);
        alert(data.id);
        // ......
    }
});

答案 1 :(得分:1)

一个特别有用的补充,如果你运行多个ajax调用是$ .ajaxSetup

$.ajaxSetup({
  type: 'post',
  dataType: 'json'
});

任何后续的ajax调用都将使用这些作为默认值。

答案 2 :(得分:0)

您必须自己指定dataType: 'json'或eval返回的数据,例如var data = eval('(function(){return '+data+'})()');

BTW信任jQuery - 如果可以,请使用dataType: 'json'