asp.net Ajax和web services

时间:2023-03-08 16:35:44
asp.net Ajax和web services

新建一个web服务

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services; /// <summary>
/// WebService1 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService { public WebService1 () { //如果使用设计的组件,请取消注释以下行
//InitializeComponent();
} [WebMethod]
public string HelloWorld() {
return "Hello World";
} [WebMethod]
public string Welcome(string user) { string username = "";
if (user == string.Empty)
{
username = "游客";
}
else
{
username = user;
}
string stumsg = "谢谢【" + username + "】选择ASP.NET";
return stumsg;
}
}

在default.aspx中

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title> <script type="text/javascript" language="javascript" >
function OnBTok_click()
{
var username = document.getElementById("TextBox1").value;
var ws = new WebService1();
ws.Welcome(username, ShowMsg);
} function ShowMsg(result)
{
var strResult = result.toString();
document.getElementById("divMsg").innerHTML = strResult;
} </script> </head>
<body>
<form id="form1" runat="server">
<div> <asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService1.asmx" InlineScript="true" />
</Services>
</asp:ScriptManager> </div>
<div>
<asp:Label ID="Label1" runat="server" Text="请输入姓名"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<input id="Button1" type="button" onclick="OnBTok_click();" value="查询" />
</div> <div id="divMsg"> </div>
</form>
</body>
</html>