我正在尝试构建一个每秒更新一些状态文本的 asp.net(c#) 页面。 现在我已经实现了一个调用另一个 PageMethod 的按钮,它会重新启动一些东西并需要一些时间。问题是,当我调用重新启动 PageMethod 时,只要重新启动方法继续进行,更新 PageMethod 就无法更新...
我写了一个小例子来说明我的意思:
我页面中的 WebMethods:
[WebMethod]
public static string Update()
{
//return "a" to see when the Update PageMethod succeeded
return "a";
}
[WebMethod]
public static string Restart()
{
//the restart will take a while
Thread.Sleep(2000);
//return "a" to see when the Restart PageMethod succeeded
return "a";
}
要更新的 html 元素:
<p id="update" style="float:left;"></p>
<p id="restart" style="float:right;"></p>
页面方法调用:
callUpdate()
function callUpdate() {
PageMethods.Update(function (text) {
//itself+text from pagemethod
$('#update').text($('#update').text() + text);
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
PageMethods.Restart(function (text) {
//itself+text from pagemethod
$('#restart').text($('#restart').text() + text);
});
setTimeout(callRestart, 1000);
}
注意:Update 也会在它完成后每秒调用一次,只是为了看看它是如何工作的
澄清一下:我希望 PageMethods 独立于其他 PageMethod 已完成执行。
我还浏览了一些链接,例如: http://esskar.wordpress.com/2009/06/30/implementing-iasyncresult-aka-namedpipeclientstream-beginconnect/
http://msdn.microsoft.com/en-us/library/aa480516.aspx
但我不认为这是我需要的(?) 而且我真的不知道如何从 Javascript(BeginXXX 和 Endxxx)调用它
*编辑:*
关于 Massimiliano Peluso,js 代码如下所示:
callUpdate()
function callUpdate() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Update",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#update').text($('#update').text() + msg.d);
}
});
setTimeout(callUpdate, 1000);
}
callRestart()
function callRestart() {
$.ajax({
type: "POST",
url: "ServicePage.aspx/Restart",
data: "{}",
contentType:
"application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#restart').text($('#restart').text() + msg.d);
}
});
setTimeout(callRestart, 1000);
}
注意:当我用新的js运行Page时,出现了和以前完全一样的问题:Update方法在Restart方法完成之前什么也做不了。
最佳答案
您应该改为使用异步调用来调用页面方法。
请看下面。这是一种使用 JQuery 调用页面方法的通用方法
$.ajax({
type: "POST",
url: "PageName.aspx/MethodName",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
您应该使用此代码来替换页面方法调用
PageMethods.Restart(function (text))
PageMethods.Update(function (text))
关于c# - asp.net 从 Javascript 异步调用 WebMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7158055/