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>