
/// <summary>
/// TestServer 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消注釋以下行。
// [System.Web.Script.Services.ScriptService]
public class TestServer : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
[WebMethod]
public string GetAge(string id)
{
return "ID為:" + id + "的年齡為:"+new Random().Next(10,41);
}

通常是把WebServer發布到iis,然後在另一個程序中調(這裡為了方便直接在本程序中調用演示)

然後看項目Service References文件夾

protected void Page_Load(object sender, EventArgs e)
{
ServiceReference1.TestServerSoapClient testServer = new ServiceReference1.TestServerSoapClient();
string str1= testServer.HelloWorld();
string str2 = testServer.GetAge("b101");
Response.Write(str1 + "," + str2);
}
有結果輸出剛調用成功了。
2.添加一個WebServerData.html頁面
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src=" http://libs.baidu.com/jquery/1.11.1/jquery.min.js "></script>
<script type="text/javascript">
$(function () {
$("#getdata").click(function () {
$.ajax({
type: 'POST',
url: 'TestServer.asmx/GetAge',
data: '{ id:"bb101"}',
dataType: 'json',
contentType: "application/json",
success: function (data) {
$("#data").append(data.d);
}
});
});
});
</script>
</head>
<body>
<a id="getdata" href="javascript:void(0);">獲取webservice數據</a>
<div id="data"></div>
</body>
</html>
點擊a顯示下圖則成功。
