Javascript 如何使用asp.net web服务仅刷新asp.net 4.0网页的一小部分,而不编辑任何其他部分
我知道如何编写web服务,但到目前为止,我将其与随时准备好的脚本一起使用。这次我想做的是,让一个web服务返回一个字符串,我想在网页的一部分显示这个字符串。该部件可能在更新面板内,也可能不在更新面板内。我知道如何使用jquery。所以我的问题是如何每5秒钟调用一个web服务,并用web服务的结果更新网页的一部分。此更新不应中断页面的任何部分,也不应导致回发 我该怎么做 asp.net 4.0,c#4.0您不能仅使用c#来实现这一点-这有一个重要的客户端部分,因此您需要使用javascript 您可以使用AJAX轮询Web服务并更新页面的某个部分。使用或每5秒重复一次通话Javascript 如何使用asp.net web服务仅刷新asp.net 4.0网页的一小部分,而不编辑任何其他部分,javascript,jquery,asp.net,web-services,Javascript,Jquery,Asp.net,Web Services,我知道如何编写web服务,但到目前为止,我将其与随时准备好的脚本一起使用。这次我想做的是,让一个web服务返回一个字符串,我想在网页的一部分显示这个字符串。该部件可能在更新面板内,也可能不在更新面板内。我知道如何使用jquery。所以我的问题是如何每5秒钟调用一个web服务,并用web服务的结果更新网页的一部分。此更新不应中断页面的任何部分,也不应导致回发 我该怎么做 asp.net 4.0,c#4.0您不能仅使用c#来实现这一点-这有一个重要的客户端部分,因此您需要使用javascript 您
看看API。您正在寻找的是AJAX:)
是一个很好的入门指南。您可以使用Javascript中的
window.setInterval
连续轮询Web服务
setInterval(function() {
// call the webservice and update the page with its response
}, 5000);
要使用jQuery调用webservice,可以使用或get
函数:
$.ajax(
url: ...
data: ... input data
success: function(response) { /* update your page with the response */ },
error: function() { /* don't forget to treat errors */ }
);
现在,更新页面取决于您得到的响应类型。假设您有一个简单的字符串(或HTML字符串)要放在div
元素中,您可以这样做:
// this is your success handler
$('#myDiv').html(response);
如果您的页面已经在使用updatepanels,那么您可以重用ms ajax库,而根本不需要jquery库 javascript:
function GetMyString() {
// Call a static page method to get your string
PageMethods.GetMyStringWebMethod(OnSucceeded, OnFailed);
}
aspx:
将asp:ScriptManager更改为启用PageMethods=“true”
如果您喜欢使用jquery,那么只需将Pagemethods调用替换为jquery.Ajax调用,将GetMyStringWebMethod.aspx作为url传入,并处理Ajax成功事件中插入的字符串。这就是我想要的部分。谢谢你的回答。但这失败了:PageMethods.GetMyStringWebMethod(OnSucceeded,OnFailed);我只是用自己的类替换了PageMethods,但失败了。如何在类内调用webservice?您需要将EnablePageMethods=“true”添加到,然后调用“PageMethods.YourMethodName”-确保“YourMethodName”是页面代码中的静态方法,并且具有“[WebMethod]”属性
function OnSucceeded(result, userContext, methodName) {
$get('yourDivContainer').innerHTML = '<b>' + result + '</b>';
setTimeout("GetMyString()", 5000);
}
function OnFailed(error, userContext, methodName) { }
function pageLoad() {
// On initial load and partial postbacks,
GetMyString();
[WebMethod]
public static string GetMyStringWebMethod()
{
return "the string";
}