我使用以下代码从服务器获取时间。
btnNoP .click函数返回正确的时间,但是asp:Button会在页面上返回警告错误。
如果单击asp:按钮,如何从document.ready成功调用webmethod?
<script type="text/javascript">
function PageMethod(fn, paramArray, successFn, errorFn)
{
var pagePath = window.location.pathname;
//Create list of parameters in the form : {"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0)
{
for (var i=0; i<paramArray.length; i+=2)
{
if (paramList.length > 0)
paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i+1] + '"';
}
}
paramList = '{' + paramList + '}';
alert(pagePath + "/" + fn);
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
dataType: "json",
success: successFn,
error: errorFn
});
}
function AjaxSucceeded (result)
{
alert(result.d);
//$("#Result").text("Result : " + result.d);
}
function AjaxFailed (result)
{
alert("Error on Page");
}
$(document).ready(function() {
$('#btnNoP').click(function() {
PageMethod("GetTime", [], AjaxSucceeded, AjaxFailed);
});
$('#btnNoParams').click(function() {
PageMethod("GetTime", [], AjaxSucceeded, AjaxFailed);
});
});
</script>
<asp:ScriptManager ID="sm" EnablePageMethods="true" EnablePartialRendering="true" runat="server"></asp:ScriptManager>
<asp:Button ID="btnNoParams" Text="Get Time" runat="server" />
<input type="button" id="btnNoP" />
[WebMethod(true)]
public static string GetTime() {
return "You called at : " + DateTime.Now.ToShortDateString() + "-" + DateTime.Now.ToShortTimeString();
}
答案 0 :(得分:0)
更改以下代码。
$('#btnNoParams').click(function() {
PageMethod("GetTime", [], AjaxSucceeded, AjaxFailed);
return false;
});
或
以下链接可能有帮助
http://cmsnsoftware.blogspot.com/2011/01/how-to-call-csharp-function-in-ajax.html
修改: - 如果您使用的是jQuery ajax,则无需在页面中添加脚本管理器。如果要将脚本管理器添加到页面,则可以直接调用web方法而不使用jQuery。请参阅上面的链接,该链接描述了如何使用JavaScript,jQuery和asp.net ajax访问Web方法。