這裡我們首先給出這個web服務:
using System;
using System.Collections;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web .Script .Services ;
/// <summary>
///WebService 的摘要說明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService ]
public class WebService : System.Web.Services.WebService {
public WebService () {
//如果使用設計的組件,請取消注釋以下行
//InitializeComponent();
}
[WebMethod]
public string HelloWorld(string instr) {
string str = "伺服器asp。net ajax得到了你輸入的資訊:"+instr +"<br/>你的ip地址是:";
str += System.Web.HttpContext.Current.Request.UserHostAddress;
str += "<br/>目前時間:";
str += System.DateTime.Now.ToLocalTime();
return str;
}
}
下面是源檔案:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id ="head1" runat="server">
<title>hello</title>
<script type ="text/javascript" language ="javascript" >
//web服務成功後調用回呼函數
function OnShow(result)//這裡的參數是web函數調用後返回的值
{
var s=$get("msg");//也可以用document.getElementById("msg")擷取html控制項“msg”;
s.innerHTML=result .toString ();
}
function SayHello()
{
var fs=WebService;//這裡的WebService是web服務中的類(不要和檔案名稱搞反了)
fs .HelloWorld(document.getElementById("testmsg").value,OnShow);//OnShow 是web函數調用成功後調用的函數並且把傳回值傳給它
return false ;
}
</script>
<style type="text/css">
#Text1
{
width: 206px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="WebService.asmx" />//web服務的調用
</Services>
</asp:ScriptManager>
<div style="width: 400px; margin-top :50px; text-align :center ">
<input id="testmsg" type="text" value="hello ajax" /><br />
<asp:Button ID="Button1" runat="server" onclientclick="return SayHello()"
Text="提交給WEB服務" />
<br />
</div>
<div id ="msg" >資訊從這裡顯示。。。。。</div>
</form>
</body>
</html>