我有兩個來自jQuery的Web服務的Ajax調用。jQuery Ajax調用Web服務似乎是同步的
第一個調用(GetMessages
)以javascript(setInterval
)開始間隔,並返回存儲在會話變量中的字符串數組。
第二個電話(UploadUsers
)上傳用戶並在方法GetMessages
中保存要返回的會話中的狀態。因此,UploadUsers會將消息添加到會話,並且GetMessages會檢索消息並將其顯示給客戶端。
問題是即使我異步調用兩種方法,GetMessages
一直等到UploadUsers
完成。它只是加載。
我甚至把添加的每個用戶之間的Thread.Sleep,我希望有GetMessages
回報「1/10的用戶已添加」,「2/10的用戶已添加」,在每一個單獨的呼叫。
發生什麼是GetMessages
不會返回任何內容,直到UploadUsers
完成,然後將所有文本一次。
我有很多的代碼,所以我不知道要放什麼東西,但這裏有雲:
UploadUsers.aspx
callAsynchMethod('ClientStatusHandler.asmx/GetMessages',
'', printMessages, stopPollingError);
callAsynchMethod('ClientStatusHandler.asmx/StartRetrievingLeads',
data, stopPolling, stopPollingError);
Site.js
function callAsynchMethod(url, keyValue, callBack, callBackError) {
$.ajax({
type: "POST",
url: url,
data: keyValue,
contentType: "application/json; charset=utf-8",
success: callBack,
error:callBackError
});
}
ClientStatusHandler.asmx.cs
const string key = "LUMessages";
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public string[] GetMessages()
{
if (Session[key] != null)
{
string[] messages = ((IList<string>)Session[key]).ToArray();
((IList<string>)Session[key]).Clear();
return messages;
}
return new string[] { };
}
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public string[] UploadUsers()
{
//This function adds a user and calls SaveMessageToQueue
//for every user.
//I see the message being entered into the session and
//I call Thread.Sleep(10000)
//between messages.
}
private void SaveMessageToQueue(string m)
{
IList<string> messageQueue = (List<string>)HttpContext.Current.
Session["LUMessages"];
messageQueue.Add(m);
}
我取代了代碼中的getMessages方法返回一個硬編碼字符串數組來測試它,我仍然得到了等待,即使他不會接近會議。 – Eitan 2012-01-29 10:36:37
@Eitan您需要將EnableSessio設置爲false(或只讀) – Aristos 2012-01-29 11:09:57