在asp.net 2010中,在建立web应用时,默认已经在script目录下有了jquery的相关文件了,十分方便。下面介绍如何在jquery中调用
websevice.
首先,建立一个webservice如下:
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
[System.Web.Script.Services.ScriptService]
public class HelloWorld : System.Web.Services.WebService
{
[WebMethod]
public string PrintMessage()
{
return "Hello World";
}
}
2 在前端页面中,如下的javscript就可以了,其实还是很容易理解的:
<asp:Button ID="Button1" runat="server" OnClientClick="CallWebServiceFromJquery()" Text="Button" />
script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"> </script>
<script language="javascript" type="text/javascript">
function CallWebServiceFromJquery() {
$.ajax({ type: "POST", url: "HelloWorld.asmx/PrintMessage",
data: "{}", contentType: "application/json; charset=utf-8",
dataType: "json", success: OnSuccess, error: OnError
});
}
function OnSuccess(data, status)
{
<script language="javascript" type="text/javascript">
function CallWebServiceFromJquery() {
$.ajax({ type: "POST", url: "HelloWorld.asmx/PrintMessage",
data: "{}", contentType: "application/json; charset=utf-8",
dataType: "json", success: OnSuccess, error: OnError
});
}
function OnSuccess(data, status)
{
alert(data.d);
}
function OnError(request, status, error)
{
function OnError(request, status, error)
{
alert(request.statusText);
}
</script>
</script>
3 最后是BUTTON,注意用onclientclick