博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在JavaScript中调用ASP.NET WebService的简单方法
阅读量:4315 次
发布时间:2019-06-06

本文共 4774 字,大约阅读时间需要 15 分钟。

      客户端 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
>

转载于:https://www.cnblogs.com/JoinZhang/archive/2010/09/15/1826684.html

你可能感兴趣的文章
《小强升职记——时间管理故事书》读书笔记
查看>>
Alpha 冲刺(3/10)
查看>>
Kaldi中的Chain模型
查看>>
spring中的ResourceBundleMessageSource使用和测试示例
查看>>
css规范 - bem
查看>>
UVALive 6145 Version Controlled IDE(可持久化treap、rope)
查看>>
mysql 将两个有主键的表合并到一起
查看>>
底部导航栏-----FragmentTabHost
查看>>
在linux中安装jdk以及tomcat并shell脚本关闭启动的进程
查看>>
apk,task,android:process与android:sharedUserId的区别
查看>>
前端实现文件的断点续传
查看>>
转:spring4.0之二:@Configuration的使用
查看>>
【Android开发】交互界面布局详解
查看>>
状态机编程思想(1):括号内外字符串统计
查看>>
K-Means聚类和EM算法复习总结
查看>>
[转]Bat脚本处理ftp超强案例解说
查看>>
P3901 数列找不同
查看>>
利用无线网络数据包分析无线网络安全
查看>>
MEMBER REPORT
查看>>
[HAOI2006]受欢迎的牛
查看>>