2012-02-25 43 views
0

可能重複:
Synchronous calls with jquery從函數的返回值與Ajax調用

我試圖返回從包含Ajax調用的函數的值(請參見下面的代碼)。

returnValue變量在警報和返回時未定義。任何人都可以幫忙嗎?

function getLightboxImages(){ 

    var returnValue; 

    jQuery.ajax({ 
     url: "http://test.domain.com/WebService.svc/GetAllI", 
     data: { id: "2", hash:"MaD01" }, 
     async: false, 
     dataType: "jsonp", 
     success: function (result) { 
      returnValue = result 
     } 
    }); 

    alert(returnValue); 

    return returnValue; 
} 
+0

成功函數的AJAX請求完成時異步調用。 – mikeycgto 2012-02-25 16:48:01

回答

2

警報將不得不放在成功函數中,因爲這是在ajax返回時調用的。您上面的內容將發送請求,然後嘗試在請求完成之前提醒返回的值。

+0

@Xander:是的,它是異步的。無法創建同步的JSONP請求。 – Guffa 2012-02-25 17:22:57

0

您無法進行同步JSONP請求。

使用回調,而不是回報:

function getLightboxImages(callback) { 
    jQuery.ajax({ 
    url: "http://test.domain.com/WebService.svc/GetAllI", 
    data: { id: "2", hash:"MaD01" }, 
    dataType: "jsonp", 
    success: function (result) { 
     callback(result); 
    } 
    }); 
} 

用法:

getLightboxImages(function(result){ 
    alert(result); 
}); 
+0

@Xander:是的,它是異步的。如果您發出JSONP請求,則會忽略'async'設置,因爲*無法*發出同步JSONP請求。 – Guffa 2012-02-25 17:22:38

1
function getLightboxImages(){ 
    var returnValue; 

    jQuery.ajax({ 
     url: "http://test.domain.com/WebService.svc/GetAllI", 
     data: { id: "2", hash:"MaD01" }, 
     async: false, 
     dataType: "jsonp", 
     success: function (result) { 
      returnValue = result 
     } 
    }); 

    alert(JSON.stringify(returnValue)); 

    return returnValue; 
} 

跨域請求只能是異步,如跨域請求依賴於動態腳本標記,它永遠不會是同步的,並且必須使用數據類型json和GET方法。

對於相同的域請求,請在提醒之前嘗試對json對象進行字符串化,如上所述!

2

試試這段代碼,對於JSONP你必須使用回調函數而不是成功的方法。

$.ajax({ 
     url: 'http://test.domain.com/WebService.svc/GetAllI', 
     type: 'GET', 
     data: "{}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "jsonp", 
     jsonp: "callback", 
     jsonpCallback: "jsonpCallbackfunction", 
     error: function() { 
      alert("Error in Jsonp"); 
     } 
    }); 

    function jsonpCallbackfunction(responseData) { 
     alert(responseData); 
    } 

http://cmsnsoftware.blogspot.com/2012/02/how-to-use-cross-domain-ajax-request.html#0