多个ajax请求未定义

时间:2016-02-27 15:15:20

标签: javascript jquery ajax

我已经阅读了大多数ajax请求解决方案....我设法使用if语句嵌套来运行两个请求..我的代码是

$(document).on('click', '.postTitle', function(e) {
    e.preventDefault();
    var id = $(this).data('id');
    var request = $.ajax({
            url: 'includes/functions.php?job=single_blog',
            cache: false,
            data: 'id=' + id,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            type: 'get'
        });

    var request2 = $.ajax({
            url: 'includes/functions.php?job=blog_comment',
            cache: false,
            data: 'id=' + id,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            type: 'get'
        });

    request.done(function (output) {
        if (output.result === 'success') {
            request.done(function (output2) {
                if (output2.result === 'success') {
                    var single_blog = output.data[0].single_blog;
                    var blog_comment = output2.data[0].blog_comment;
                    $('.blog').empty().append(single_blog);
                    console.log(blog_comment);
                } else {
                console.log('ajax2 failed', 'error2');
                }
            });
        } else {
            console.log('Information request failed', 'error');
        }
    });
    request.fail(function (jqXHR, textStatus) {
        console.log('error');
    });

});

当我在var single_blog上执行console.log时,我得到了值,但是当我在var blog_comment上尝试时,我得到了未定义的....我在哪里错过了它?

3 个答案:

答案 0 :(得分:1)

尝试使用$.when.apply(),一个.done()

$.when.apply($, [request, request2])
.done(function(output, output2) {
  // do stuff with responses from `request`, `request2`
  if (output[0].result === "success" 
      && output2[0].result === "success") {
       var single_blog = output.data[0].single_blog;
       var blog_comment = output2.data[0].blog_comment;
       $(".blog").empty().append(single_blog);
       console.log(blog_comment);
  } 
})
.fail(function() {
   console.log("error");
})

答案 1 :(得分:0)

我认为不是

request.done(function (output2) {

应该是

request2.done(function (output2) {

答案 2 :(得分:0)

request适用于single_blogrequest2适用于blog_comment

您将小错误更改为

request.done(function (output) {
                if (output.result === 'success') {
                    request2.done(function (output2) {
                        if (output2.result === 'success') {
                            var single_blog = output.data[0].single_blog;
                            var blog_comment = output2.data[0].blog_comment;
                            $('.blog').empty().append(single_blog);
                    console.log(blog_comment);
                } else {'ajax2 failed', 'error2'}
            })