2016-02-27 62 views
0

我看了大部分的多個Ajax請求解決的....我設法讓使用if語句的嵌套都要求運行..我的代碼是多個AJAX請求越來越不確定

$(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'); 
    }); 

}); 

當我這樣做控制檯.log on var single_blog,我得到的值,但是當我嘗試它在var blog_comment我得到未定義....我在哪裏錯過了?

回答

0

我覺得

request.done(function (output2) { 

相反,它應該是

request2.done(function (output2) { 
0

requestsingle_blogrequest2blog_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'} 
      }) 
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

'output'和'output2'將是一個數組,而不是對象 – charlietfl

+1

@charlietfl見更新後 – guest271314