JavaScript 调用 ASP.NET WebService 的简单方法

文章转自:http://dotnet.aspx.cc/file/call-aspnet-web-service-using-javascript.aspx

客户端 JavaScript 调用 ASP.NET WebService 的方法除了采用 WebServer.htc 构造 SOAPAction 的方法外,下面介绍一个采用 Ajax 调用的简单方法,并且可以传递参数。其实,ASP.NET WebService 就是一个网站,所以,Request 对象是可用的,这样,传递参数就很容易了。下面是一个WebService1.asmx的代码

ASMX 代码

<%@ WebService Language="C#" CodeBehind="WebService1.asmx.cs" Class="WebService1" %>

 

C# 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;


  
/// <summary>
  
/// Summary description for WebService1
  
/// </summary>
  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  [System.ComponentModel.ToolboxItem(
false)]
  
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
  // [System.Web.Script.Services.ScriptService]
  public class WebService1 : System.Web.Services.WebService
  {
    [WebMethod]
    
// 字符串返回测试
    public string GetServerTime()
    {
      
return "当前服务器时间:" + DateTime.Now.ToString();
    }

    [WebMethod]
    
// long 类型返回测试
    public long GetServerTimeTicks()
    {
      
return DateTime.Now.Ticks;
    }

    [WebMethod]
    
// Datatable返回测试
    public DataTable GetTestDataTable()
    {
      DataTable dt =
new DataTable("TestTable");
      DataRow dr;
      dt.Columns.Add(
new DataColumn("id", typeof(Int32)));
      dt.Columns.Add(
new DataColumn("text", typeof(string)));
      
for (int i = 0; i < 6; i++)
      {
        dr = dt.NewRow();
        dr[
0] = i;
        dr[
1] = "列表项目 " + i.ToString();
        dt.Rows.Add(dr);
      }
      
return dt;
    }

    [WebMethod]
    
// List 类型测试
    public List<User> GetTestUser()
    {
      
//传递参数传测试
      string param = this.Context.Request.QueryString["param"];
      
if (param == null) param= this.Context.Request.Form["param1"];
      List<User> u_list =
new List<User>();
      
for (int i = 0; i < 10; i++)
      {
        User u =
new User();
        u.Name =
"LoginName" + i.ToString() + " param = " + param;
        u.Title =
"孟宪会" + i.ToString();
        u_list.Add(u);
      }
      
return u_list;
    }

    
//定义一个对象 User
    public class User
    {
      
public String Name { get; set; }
      
public String Title { get; set; }
    }
  }

 客户端调用的代码:

HTML 代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  
<title>JavaScript 调用 ASP.NET Web 服务测试</title>
  
<script type="text/javascript">
    
var xmlHttp = null;
    
function createXMLHttpRequest() {
      
try {
        
if (window.XMLHttpRequest)
          xmlHttp =
new XMLHttpRequest();
        
else if (window.ActiveXObject)
          xmlHttp =
new ActiveXObject("Microsoft.XMLHTTP");
      }
      
catch (ex) { }
    }

    
function AsynRequest() {
      createXMLHttpRequest();
      
if (xmlHttp == null) {
        alert("
不能创建 XmlHttpRequest 对象");
        
return;
      }
      xmlHttp.open("GET", "WebService1.asmx/GetTestUser?param=net_lover",
true);
      xmlHttp.setRequestHeader("Connection", "close");
      xmlHttp.onreadystatechange =
function () {
        
if (xmlHttp.readyState == 4) {
          
if (xmlHttp.status == 200) {
            
var userList = xmlHttp.responseXML.getElementsByTagName("User");
            
for (i = 0; i < userList.length; i++) {
              document.getElementById("get1").innerHTML += userList[i].getElementsByTagName("Name")[0].firstChild.nodeValue + "
";
              document.getElementById("get1").innerHTML += userList[i].getElementsByTagName("Title")[0].firstChild.nodeValue + "<br/>";
            }
          }
        }
      };
      xmlHttp.send();
    }

    
function AsynPostRequest() {
      createXMLHttpRequest();
      
if (xmlHttp == null) {
        alert("
不能创建 XmlHttpRequest 对象");
        
return;
      }
      
var data = "param1=abc";
      xmlHttp.open("POST", "WebService1.asmx/GetTestUser?t=" + Date.parse(
new Date()), true);
      xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlHttp.setRequestHeader("Content-length", data.length);
      xmlHttp.setRequestHeader("Connection", "close");
      xmlHttp.onreadystatechange =
function () {
        
if (xmlHttp.readyState == 4) {
          
if (xmlHttp.status == 200) {
            
var userList = xmlHttp.responseXML.getElementsByTagName("User");
            
for (i = 0; i < userList.length; i++) {
              document.getElementById("post1").innerHTML += userList[i].getElementsByTagName("Name")[0].firstChild.nodeValue + "
";
              document.getElementById("post1").innerHTML += userList[i].getElementsByTagName("Title")[0].firstChild.nodeValue + "<br/>";
            }
          }
        }
      };
      xmlHttp.send(data);
    }
  
</script>
</head>
<body>
<input type="button" value="GET 方法调用" onclick="AsynRequest()" />
<input type="button" value="POST方法调用" onclick="AsynPostRequest()" />
<div id="get1"></div>
<div id="post1"></div>
</body>
</html>

 需要注意的是:使用此方法需要在web.config里加入以下的配置:

web.config 代码

<system.web>
  
<webServices>
    
<protocols>
      
<add name = "HttpPost" />
      
<add name = "HttpGet" />
    
</protocols>
  
</webServices>
</system.web>

 另外,也可以采用ASP.NET内置的方法进行调用,方法如下:

ASPX 代码

<%@ Page Language="C#" %>
<script runat="server">  
  public class User
  {
    public String UserName { set; get; }
    public Int32 Count { set; get; }
    public User() { }
  }
  [System.Web.Services.WebMethod]
  [System.Web.Script.Services.ScriptMethod]
  public static List<User> GetUsers(
int count)
  {
    List<User> p =
new List<User>();
    User x =
new User();
    x.UserName = "AA";
    x.Count = 20;
    p.Add(x);

    x =
new User();
    x.UserName = "AA";
    x.Count = count;
    p.Add(x);
    
return p;
  }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  
<script type="text/javascript">
    
function GetData() {
      PageMethods.GetUsers((
new Date()).getSeconds(), OnGetProductsComplete);
    }
    
function OnGetProductsComplete(result) {
      
for (i = 0; i < result.length; i++) {
        alert(result[i].UserName + " = " + result[i].Count);
      }
    }
  
</script>
</head>
<body>
  
<form id="form1" runat="server">
  
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
  
<input id="Button1" type="button" value="测试" onclick="GetData()" />
  
</form>    
</body>
</html>


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值