2011-10-24 33 views
1

是否有可能將javascript中的msg變量從回調函數中退出?我試過這樣做,但得到一個null,即使msg變量在回調函數的作用域中有數據。從回調函數中返回JSON數據

var msg = load(); 


function load() 
{ 
    $.ajax({ 
    type: "POST", 
    url: "myPage.aspx/MyMethod", 
    data: jsonText, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function (msg) { return msg; // Doesn't return anything because 
              //it's automatically called on success??? 
    }, 
    failure: function() { alert("Failure"); } 
    }); 
} 
+0

可能重複的[Return「success:」方法的數據?](http://stackoverflow.com/questions/7753844/return-success-methods-data) – Quentin

+0

@Quentin:這個問題實際上也是重複的和其接受的答案是相當差),[這另一個](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success)有更好的答案(雖然仍然沒有演示回調和單獨的同步請求)。 –

回答

0

由於XHR是異步的,您需要將回調傳遞給load()

順便說一句,msg應該包含undefined如果你沒有明確地返回任何東西。

3

不適用於異步請求,這是正常類型的ajax請求和首選類型。這是因爲load在您收到服務器的回覆之前會返回,所以顯然它不能返回msg。相反,有load接受回調:

load(function(msg) { 
    // Use msg here 
}); 

function load(callback) 
{ 
    $.ajax({ 
     type: "POST", 
     url: "myPage.aspx/MyMethod", 
     data: jsonText, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     success: function (msg) { 
      // Call our callback with the message 
      callback(msg); 
     }, 
     failure: function() { 
      // Call our callback with an indication things failed 
      callback(null); // Or however you want to flag failure 
     } 
    }); 
} 

如果絕對少不了,你可以通過設置在$.ajax選項(這是該文檔的鏈接),然後再去做這樣async: false使用同步請求:

var msg = load(); 

function load(callback) 
{ 
    var result; 
    $.ajax({ 
     type: "POST", 
     url: "myPage.aspx/MyMethod", 
     data: jsonText, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     async: false, 
     success: function (msg) { 
      // Set the `result` value here. We can't *return* it 
      // here because, of course, that would just return it 
      // from our `success` function. 
      result = msg; 
     }, 
     failure: function() { 
      result = null; // Or however you want to flag failure 
     } 
    }); 

    // Because we've made the request synchronous, we won't get here 
    // until the ajax call is complete and `result` has been set by 
    // the callbacks above; we can now return it. 
    return result; 
} 

同步請求作出較差的用戶體驗,而且,幾乎從來沒有必要的,所以應避免多儘可能。