在asp.net2.0环境中用Ajax调用WebService方法

Ajax调用WebService需要在类前面加[ScriptService]属性

但是在.net2.0中默认是无法引用的,需要手动添加System.Web.Extensions.dll、System.Web.Extensions.Design.dll文件到Bin文件夹中然后添加引用。

下面是一个小例子,展示用法。

Default.aspx页面如下

<!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>Test</title>
<script src="jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
</head>
<body>
<div>
<input type="text" id="str" value="test" />
<input type="button" onclick="getStr(document.getElementById('str').value)" value="点击我" />
</div>
</body>
</html>

页面中只有一个文本输入框和一个按钮,再看看script.js代码:

 1 function getStr(str) {
2 $.ajax({
3 url: "/TestService.asmx/GetStr",
4 type: "post",
5 dataType: "json",
6 contentType: "application/json;charset=utf-8",
7 data: "{'str':'" + str + "'}",
8 success: function(data) {
9 alert(data);
10 },
11 error: function(x, e) {
12 alert("失败!!");
13 }
14 });
15 }

请求的url形式是"/TestService.asmx/GetStr",传入参数"str"的值,获取TestService.asmx中的GetStr方法的返回值,TestService.asmx代码如下:

 1 using System.Web.Script.Services;
2 using System.Web.Services;
3
4 namespace Web
5 {
6 /// <summary>
7 /// TestService 的摘要说明
8 /// </summary>
9 [WebService(Namespace = "http://tempuri.org/")]
10 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
11 [System.ComponentModel.ToolboxItem(false)]
12 [ScriptService]
13 public class TestService : System.Web.Services.WebService
14 {
15
16 [WebMethod]
17 [ScriptMethod(UseHttpGet = false)]
18 public string GetStr(string str)
19 {
20 return "Hello " + str;
21 }
22 }
23 }

这一步注意在TestService类前加[ScriptService]

最后需要在Web.config配置文件中configuration节点下system.web节点里面加入

1 <httpHandlers>
2 <remove verb="*" path="*.asmx"/>
3 <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
4 </httpHandlers>


很简单的一个GetStr方法,该例子主要演示一下在.net2.0环境中Ajax调用WebService的方法。

最后附上该例子源码,里面含有了上面说到的2个dll文件。

源码下载

转载于:https://www.cnblogs.com/wontonJ/archive/2011/10/26/2225629.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值