最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Debugging jQuery AJAX response: what I'm doing wrong? - Stack Overflow

programmeradmin3浏览0评论
$.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);
    // ......
});

The first alert gives:{"id":"2","success":true}, but the second: undefined

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

The first alert gives:{"id":"2","success":true}, but the second: undefined

Share Improve this question edited Mar 1, 2019 at 14:52 user3307073 asked Nov 8, 2009 at 12:36 DerkDerk 1812 gold badges2 silver badges6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

You need to specify your anticipated returned data type as 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);
        // ......
    }
});

An especially useful addition, if you run multiple ajax calls is $.ajaxSetup

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

Any subsequent ajax calls will use these as the defaults.

You have to specify dataType: 'json' or eval returned data yourself like this var data = eval('(function(){return '+data+'})()');

BTW trust jQuery - use dataType: 'json' if you can.

发布评论

评论列表(0)

  1. 暂无评论