2012-04-09 68 views
0

我已經創建了一個web服務的調用來自jquery ajax函數。但是,即使異步設置爲true,則不能以異步方式運行..使用jQuery ASP.NET異步AJAX調用ASP.NET不工作

我的ASP.NET Web服務代碼

<System.Web.Services.WebMethod()> _ 
Public Shared Function sampleService(ByVal ttid As String) As String 
Threading.Thread.Sleep(5 * 1000) 
Return "Hello World" 
End Function 

JQuery的呼叫腳本

<script language="javascript"> 
$(function() { 
    var tempParam = { 
     ttid: 100 
    }; 

    var param = $.toJSON(tempParam); 
    $.ajax({ 
     type: "POST", 
     url: "testservice.aspx/sampleService", 
     data: param, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     async: true, 
     error: function() { 
      alert("Error"); 
     }, 
     success: function(msg) { 
      alert("Success") 
      alert(msg.d) 
     } 
    }); 
});​ </script> 

在這裏,我將其設置爲異步=真正。即使這樣,我在5秒後就會收到成功消息。這意味着不是異步的。我相信如果async = true,它不會等待來自webserivice的消息。這實際上是我的要求。

+0

順便說一下,您已設置的選項值; async:true是默認值。 – 2012-04-11 13:50:09

回答

3

成功功能是回調;它被設計爲在收到響應之後被調用。如果在服務器線程執行完成之前調用成功或錯誤,那麼如何確定成功或錯誤?睡眠呼叫會暫停當前的服務器線程,所以當然您的響應需要五秒鐘才能恢復。

異步部分將應用於直接跟在您的ajax後的Javascript代碼。例如:

<script language="javascript"> 
$(function() { 
    var tempParam = { 
     ttid: 100 
    }; 

    var param = $.toJSON(tempParam); 
    $.ajax({ 
     type: "POST", 
     url: "testservice.aspx/sampleService", 
     data: param, 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     async: true, 
     error: function() { 
      alert("Error"); 
     }, 
     success: function(msg) { 
      alert("Success") 
      alert(msg.d) 
     } 
    }); 
    alert('This alert is asynchronous! We do not know yet if the ajax call will be successful because the server thread is still sleeping.'); 
});​ </script> 
+0

嗨丹...謝謝你的明確信息。但我還有一個疑問。想象一下,我的web服務包含一些長時間運行的代碼,我們使用ajax進行了web服務調用。我的疑問是,如果用戶關閉該瀏覽器窗口,該Web服務代碼執行是否會暫停,或者即使在瀏覽器關閉之後,它仍會繼續,直到所有代碼都在webservice中執行爲止。 – 2012-04-09 11:09:27

+0

@ user954093我不能說權威,因爲我從來沒有遇到過這個問題,但我認爲你的服務器端進程仍然可以完成獨立於它被調用的瀏覽器狀態的執行。當然,除非您正在跟蹤服務器端的會話狀態,並且明確表示要結束會話纔會中止。 – 2012-04-09 14:16:47

+0

謝謝兄弟。我試過了,正在後臺工作。乾杯老闆.. – 2012-04-09 17:25:42

-1

您是否檢查過web服務設置爲在腳本中執行。

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 

[System.Web.Script.Services.ScriptService] 

請檢查併發送更新,如果它工作與否。

+0

Web服務工作正常。 – 2012-04-09 06:02:55

+0

嘿@AndrewBarber我只是交叉檢查!有時會發生,我們一路工作,忘記一條簡單的線路。 – Murtaza 2012-04-11 12:26:16

2

這裏我把它設置爲async = true。即使這樣,我在5秒後就會收到成功消息。這意味着不是異步的。我相信如果async = true,它不會等待來自webserivice的消息。

沒有,async意味着工作線程被鎖定並不會執行任何其他代碼(會凍結在窗口...),直到它從服務器獲取其請求的響應。
這並不意味着你會得到一個答案我一會兒!