2013-04-30 29 views
0

我有一個函數X1具有類似下面回調的JavaScript

var result; 

function x1() 
{ 
    $.ajax({ 
     type: Type, //GET or POST or PUT or DELETE verb 
     url: Url, // Location of the service   
     contentType: ContentType, // content type sent to server 
     dataType: DataType, //Expected data format from server   
     success: function (msg) {//On Successfull service call 
      result = msg.GetUrlContentResult; 
     }, 
     error: function (xhr, ajaxOptions, thrownError) { 

     } 
    }); 
} 

我還有一個功能X11調用X1取決於變量結果的這個值是全局變量一個AJAX調用服務器的東西。

function x11() 
{ 
    x1(); 
    if (result==something) 
    {do something} 
} 

問題是因爲X1()是異步函數結果,如果結果獲取的執行時沒有設置。我想我必須做一些類型的回調,看回調的一些例子我是小新這個任何幫助,如何正確安裝時,它從X1返回回調使結果的值設置?我有一個以上的函數調用X1()

+0

如果你把「如果(結果==東西){做某事}」成功回調函數中的一部分?如果必要的話,你也可以將它添加到錯誤回調函數中。 – HartleySan 2013-04-30 00:35:24

+0

我有一個以上的函數調用X1()和diffrently處理結果 – 2013-04-30 00:38:32

回答

2

什麼你正在試圖做的其實就是這樣簡單的東西:(編輯動態回調)

function x1(callback) 
{ 
    $.ajax({ 
     type: Type, //GET or POST or PUT or DELETE verb 
     url: Url, // Location of the service   
     contentType: ContentType, // content type sent to server 
     dataType: DataType, //Expected data format from server   
     success: callback, 
     error: function (xhr, ajaxOptions, thrownError) { 

     } 
    }); 
} 

x1(x11); 

你將不得不修改X11功能接受msg參數,並更新result變量:

function x11(msg) { 
    result = msg.GetUrlContentResult; 
    //... 
} 
+0

但我有功能X1可以由多個功能不僅僅是X11 – 2013-04-30 00:34:19

+0

好被調用,將更新的答案 – 2013-04-30 00:35:46

+0

可以還實現sucess:X1上,然後在成功的底部做回調? sucess:{//做一些 回調} – 2013-04-30 00:51:51

3

單個Ajax調用可以有多個成功的處理程序。返回從x1()jqXHR object,並使用從x11()綁定額外success處理它的.done() method

function x1() 
{ 
    return $.ajax({ 
     ... 
    }); 
} 
function x11() 
{ 
    x1().done(function(msg) { 
     // this is an additional success handler 
     // both handlers will be called 
    }); 
} 
+0

做我需要添加旁阿賈克斯$回報? – 2013-04-30 00:40:27

+0

@JustinHomes - 是的。否則,'x1()'返回'undefined',當你試圖調用'x1()。success()'時你會得到一個運行時錯誤。沒有辦法「成功」未定義。 – gilly3 2013-04-30 00:42:07

+0

@JustinHomes - 如果你真正的功能實際上並沒有立即作出AJAX調用後退出,就可以了'jqXHR'對象存儲在一個變量和函數的最後返回變量。是的,謝謝 - – gilly3 2013-04-30 00:45:07