asp.net Ajax和web services

新建一个web服务

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Services;
 6 
 7 /// <summary>
 8 /// WebService1 的摘要说明
 9 /// </summary>
10 [WebService(Namespace = "http://tempuri.org/")]
11 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
12 // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。 
13  [System.Web.Script.Services.ScriptService]
14 public class WebService1 : System.Web.Services.WebService {
15 
16     public WebService1 () {
17 
18         //如果使用设计的组件,请取消注释以下行 
19         //InitializeComponent(); 
20     }
21 
22     [WebMethod]
23     public string HelloWorld() {
24         return "Hello World";
25     }
26 
27 
28     [WebMethod]
29     public string Welcome(string user)
30 
31     {
32 
33         string username = "";
34         if (user == string.Empty)
35         {
36             username = "游客";
37         }
38         else
39         {
40             username = user;
41         }
42         string stumsg = "谢谢【" + username + "】选择ASP.NET";
43         return stumsg;
44     }
45 }

在default.aspx中

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8     <title></title>
 9 
10     <script type="text/javascript" language="javascript" >
11         function OnBTok_click()
12         {
13             var username = document.getElementById("TextBox1").value;
14             var ws = new WebService1();
15             ws.Welcome(username, ShowMsg);
16         }
17 
18         function ShowMsg(result)
19         {
20             var strResult = result.toString();
21             document.getElementById("divMsg").innerHTML = strResult;
22         }
23 
24     </script>
25 
26 </head>
27 <body>
28     <form id="form1" runat="server">
29     <div>
30     
31        <asp:ScriptManager ID="ScriptManager1" runat="server">
32            <Services>
33                <asp:ServiceReference Path="~/WebService1.asmx" InlineScript="true" />
34            </Services>
35        </asp:ScriptManager>
36     
37     </div>
38         <div>
39             <asp:Label ID="Label1" runat="server" Text="请输入姓名"></asp:Label>
40                 <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
41                 <input id="Button1" type="button" onclick="OnBTok_click();" value="查询" />
42         </div>
43 
44         <div id="divMsg">
45 
46         </div>
47     </form>
48 </body>
49 </html>

 

posted @ 2016-12-11 15:09  清风白水  阅读(149)  评论(0编辑  收藏  举报