您的位置:首页 > Web前端 > JavaScript

老孟的文章JavaScript 调用 ASP.NET WebService 的简单方法

2011-12-28 13:40 417 查看
1)客户端 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# 代码

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->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 代码

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--><!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>
另外,也可以采用ASP.NET内置的方法进行调用,方法如下:

ASPX 代码

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--><%@ 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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: