jquery调用webservice(.net)
2011-01-18 12:58 smat 阅读(289) 评论(0) 编辑 收藏 举报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";
}
首先,建立一个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)
{ alert(data.d); }
function OnError(request, status, error)
{ alert(request.statusText); }
<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)
{ alert(data.d); }
function OnError(request, status, error)
{ alert(request.statusText); }
</script>