2016-11-25 85 views
3

我想返回第二個ajaxcall作爲ajax函數的結果,任何人都可以幫助我。返回AJAX內部的AJAX調用

private ajax(url: string, method:string, data:any = null) { 
    var _this = this; 
    return this.csrfWithoutDone().done(function (res) { 
     $.ajaxSetup({ 
     headers: { 
      'X-CSRF-TOKEN': res 
     } 
     }); 
     return $.ajax({ 
     url: _this.baseUrl + url, 
     type: method, 
     data: data, 
     }); 
    }); 
    } 

的csrfWithoutDone功能:

return $.ajax({ 
     url: _this.baseUrl + '/api/csrf', 
     type: 'GET' 
    }); 

BTW:這是writen在打字稿,但如果你更換私人與功能,並刪除了:(型),它太JS工作。

+2

因爲您正在使用jquery進行http調用,所以我刪除了angular2標記。如果您認爲這不正確,請告訴我。 – echonax

+1

噢,是的,我只是添加它,因爲即時通訊在我的項目中使用它,謝謝你讓我知道。 – nusje2000

+0

也許這是你的問題的解決方案:[http://stackoverflow.com/a/22063821/4217744](http://stackoverflow.com/a/22063821/4217744) – simhumileco

回答

0

你應該做的是鏈接電話。

.done()函數是異步的。因此,當響應返回時,它會執行任何您將它作爲參數傳遞的參數。該函數的返回值無處可用。

你應該做的卻是: foo.then(函數(){/ *第1步/}),然後(函數({/第2步* /})

我建議閱讀。關於在Javascript asynchrounousity一點點

這是你要做的承諾做到這一點,我從來沒有使用jQuery的工作這麼語法可能會有所不同

編輯:我想補充一點,有沒有辦法返回初始函數中的響應值,最好的辦法是返回jqXHR對象,然後從調用者調用「then()」或「done()」。

0

你應該在你ajax函數返回一個對象,才能夠了解您的要求完成與否。既然你使用jQuery,您可以使用Deferred Objects

function ajax(url, method, data) { 
    var _this = this; 

    // Create a deferred object 
    var dfd = $.Deferred(); 

    this.csrfWithoutDone().done(function (res) { 
     $.ajaxSetup({ 
      headers: { 
       'X-CSRF-TOKEN': res 
      } 
     }); 

     $.ajax({ 
      url: _this.baseUrl + url, 
      type: method, 
      data: data, 
     }).done(function (response) { 
      // your inner ajax has been done 
      // tell your promised object and pass the response to it 
      dfd.resolve(response); 
     }); 
    }); 

    // return promised 
    return dfd.promise(); 
} 

// call your ajax function, it is a promised object 
var ajaxRequest = ajax(); 

// so you can wait for the response 
ajaxRequest.done(function (response) { 
    // your ajax has been done and you have the response 
    console.log(response); 
}); 

我已經實現了一個簡單的代碼,找出許諾的對象是如何工作的:

function ajax() { 
 
    var dfd = $.Deferred(); 
 
    
 
    setTimeout(function() { 
 
     dfd.resolve('Hello World'); 
 
    }, 1000); 
 
    
 
    return dfd.promise(); 
 
} 
 

 
var testResult = ajax(); 
 

 
testResult.done(function (response) { 
 
    alert(response); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

您也可以使用本地Promise Object,也許您需要填充,以支持所有瀏覽器,請參閱Can I Use