using System.Collections.Generic
using System.Web
using System.Web.Services
/// <summary>
///WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
public WebService()
{
//如果使用设计的组件,请取消注释以下行
//InitializeComponent()
}
[WebMethod]
public string HelloWorld()
{
return "Hellow World"
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function RequestWebService() {
//这是我们在第一步中创建的Web服务的地址
var URL = "http://localhost/YBWS/WebService.asmx"
//在这处我们拼接
var data
data = '<?xml version="1.0" encoding="utf-8"?>'
data = data + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">'
data = data + '<soap12:Body>'
data = data + '<HelloWorld xmlns="http://tempuri.org/" />'
data = data + '</soap12:Body>'
data = data + '</soap12:Envelope>'
//创建异步对象
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
xmlhttp.Open("POST", URL, false)
xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml")
xmlhttp.Send(data)
document.getElementById("data").innerHTML = xmlhttp.responseText
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="One" type="button" value="JsCallWebService" onclick="RequestWebService()" />
</div>
<div id="data">
</div>
</form>
</body>
</html>
1.Web.config中需要配置好运行ASP.NET AJAX框架相应的配置项,当然,建立一个ASP.NET AJAX Enabled Web Site项目时,Web.config已经配置好了。2.想让某个WebService可以被JS调用,需要做一下几步:
I.在这个WebService文件里用“using System.Web.Script.Services”引入这个命名空间。
II.在这个类的上面添加“[ScriptService]”属性。
III.在需要被调用的方法上添加“[WebMethod]”属性。
具体例子可以参考《ASP.NET AJAX客户端编程之旅(一)——Hello!ASP.NET AJAX》中的SayHelloService.cs的代码。
3.调用WebService的客户端页面也要做相应准备。首先就是页面中要有一个ScriptManager控件,然后需要在其中指明WebService文件的位置。如:
<Services>
<asp:ServiceReference Path="~/SayHelloService.asmx" />
</Services>
将这段代码放在<asp:ScriptManager>和<asp:ScriptManager />标签之间,就可以使得这个页面中的JS可以直接调用SayHelloService.asmx中的方法。具体代码可以参考《ASP.NET AJAX客户端编程之旅(一)——Hello!ASP.NET AJAX》中第二个例子中的Default.aspx的代码。
做好以上三项准备,这个页面中的JS代码就可以使用我们熟悉的“类名.方法名”的方法直接调用WebService中的方法了。