一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

ajax异步调用数据实例

时间:2011-07-01 编辑:简简单单 来源:一聚教程网

ajax异步调用数据实例


通过ajax在客户端调用后台代码,通过后台代码更改,修复,查询数据,并把结果返回给客户端,在客户端获取到服务器返回的数据在做相应的操作,从而实现通过HTML控件操作一些在网页特效比较难实现的功能;比如通过HTML的控件访问查询数据库教程,并把结果传给客户端显示,这方面在google地图开发应用得比较多,下面以一个简单的实例说明:

添加一个.asp教程x的页面,命名为:ajaxPKashx.aspx,全部代码如下:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ajaxPKashx.aspx.cs" Inherits="AjaxTest.ajaxPKashx" %>
 2
 3  http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4
 5  http://www.w3.org/1999/xhtml" >
 6  
 7     通过ajax实现客户端获取后台数据
 8  
 9  
10  
57    


58    

59        
60        
61    

62    

63        
64        
65    

66    

67        
68        
69    

70    

71        
72        
73    

74    

75
76

 

 


第34行中

aRequest.open("POST","sample.ashx?userid=" + userID,true);

 

 


sample.ashx 为“一般处理程序”文件,也是后台代码编写的地方,根据我的了解,这种文件系统会生成两个方法,不允许在添加任何方法,或是添加了也无效,有待验证,有比较清楚的大虾请指教,以下为该文件的全部代码:

这个方法是在创建文件时自动建立的,当我们在客户端通过

 1 using System;
 2 using System.Data;
 3 using System.Web;
 4 using System.Collections;
 5 using System.Web.Services;
 6 using System.Web.Services.Protocols;
 7
 8 namespace AjaxTest
 9 {
10     ///


11     /// $codebehindclassname$ 的摘要说明
12     ///

13     [WebService(Namespace = "http://tempuri.org/")]
14     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
15     public class sample : IHttpHandler
16     {
17
18         public void ProcessRequest(HttpContext context)
19         {
20             context.Response.ContentType = "text/plain";
21             //用户ID,接收客户端传过来的参数
22             string userID = "";
23             //传回的字符串
24             string userInfo = "";
25             //读取客户端传过来的参数
26             if(!string.IsNullOrEmpty(HttpContext.Current.Request["userid"]))
27                 userID = HttpContext.Current.Request["userid"];
28
29             //通过客户端传来的参数获取后台数据,包括对数据库的操作后返回的数据集,在此就不累赘了
30             //获取后的数据可以以JSON或XML的格式封装后以string的形式传送到客户端
31             //如果数据简单就返回一个字符串,如下:
32             userInfo = "8080,张三,2008-07-01";
33             context.Response.Write(userInfo);
34         }
35
36         public bool IsReusable
37         {
38             get
39             {
40                 return false;
41             }
42         }
43     }
44 }


我们的代码只需要写在这个方法中

public void ProcessRequest(HttpContext context)

aRequest.open("POST","sample.ashx?userid=" + userID,true);


这个方法调用这个“一般处理程序”时,系统默认调用了该方法,所以我们的处理代码和返回值都在该方法完成,这样有一个不好的地方,就是每调用一次都必须新创建一个“一般处理程序”,可以想象在项目中如果经常用到这种方法那这种文件要创建很多个,这对应项目的管理是比较郁闷的;这个问题其实也是有解决的方法,ajax调用webservice便可以解决,通过调用制定的方法和制定的返回值来实现

返回方法:

context.Response.Write(userInfo);


通过该方法可以把string类型的userInfo变量传回客户端,客户端接收到该string类型的变量即可对其操作,客户端的接收代码如下:

jsUserInfo = aRequest.responseText;

热门栏目