您的位置:知识库 » .NET技术

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

作者: 孟宪会  发布时间: 2010-07-28 16:59  阅读: 3099 次  推荐: 2   原文链接   [收藏]  

  客户端 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里加入以下的配置:
<system.web>
<webServices>
<protocols>
<add name = "HttpPost" />
<add name = "HttpGet" />
</protocols>
</webServices>
</system.web>
2
0

.NET技术热门文章

    .NET技术最新文章

      最新新闻

        热门新闻