Ajax通用类
来源:互联网 发布:淘宝网电脑客户端 编辑:程序博客网 时间:2024/05/22 14:51
在用Ajax时,一般要在每个页面添加XMLHttpRequest定义与发送请求的JavaScipt代码,使页面代码增长。本文特将页面中重复的Ajax代码封装到一个JS文件中,在需要的页面引用它就实现Ajax功能。
AjaxHelper.js文件:
- //Ajax类定义
- function AjaxHelper()
- {
- //构造函数
- var httpRequest = null;
- var requestResult = "";
- var sync = false;
- this.init();
- }
- //同步请求,默认为false
- AjaxHelper.prototype.sync=false;
- //初始化
- AjaxHelper.prototype.init = function()
- {
- try
- {
- httpRequest = new ActiveXObject("Msxml2.httpRequest");
- }
- catch (e1)
- {
- try
- {
- httpRequest = new ActiveXObject("Microsoft.httpRequest");
- }
- catch (e2)
- {
- try
- {
- httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
- }
- catch (e3)
- {
- httpRequest = null;
- }
- }
- }
- if(httpRequest == null)
- {
- alert("Error initializing AjaxHelper! Can't create XMLHttpRequest object.");
- }
- }
- //发送请求
- AjaxHelper.prototype.request = function(url, postData)
- {
- var isPost = arguments.length > 1;
- var method = isPost ? "POST" : "GET";
- httpRequest.open(method, url, this.sync);
- httpRequest.onreadystatechange = createFunction(this, "handleResponse", this.requestCallback);
- if(isPost)
- httpRequest.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
- httpRequest.send(postData);
- }
- //处理请求结果
- AjaxHelper.prototype.handleResponse = function(callbackFunc)
- {
- if (httpRequest.readyState == 4)
- {
- if (httpRequest.status == 200) //正常
- {
- callbackFunc(httpRequest.responseText);
- }
- else if (httpRequest.status == 404)
- {
- alert("Request URL does not exist.");
- }
- else if (httpRequest.status == 403)
- {
- alert("Access denied.");
- }
- else
- {
- alert("Error: status code is " + httpRequest.status + ".");
- }
- }
- }
- //处理请求结果事件,需要客户端定义
- AjaxHelper.prototype.requestCallback = function(result){}
- //将有参数的函数封装为无参数的函数
- function createFunction(obj, funcName)
- {
- var args = [];
- if(!obj)
- obj = window;
- for(var i=2; i<arguments.length; i++)
- args.push(arguments[i]);
- return function()
- {
- obj[funcName].apply(obj, args);
- }
- }
其中最后一个createFunction函数是将有参数的函数封装为无参数的函数,使客户可以用事件方式来处理请求结果。
使用方式:
1、在页面中添加JS引用
- <script type="text/jscript" language="javascript" src="AjaxHelper.js"></script>
2、定义请求结果处理函数
- function handleResult(result)
- {
- //处理代码
- }
3、使用Ajax请求
- function requestData()
- {
- var ajax = new AjaxHelper();
- ajax.requestCallback = handleResult;
- ajax.request("请求页面URL");//GET
- //ajax.request("请求页面URL", postData);//POST
- }
- Ajax通用类
- AJAX开发的通用类
- Ajax 通用小模块
- Ajax通用函数
- 一套通用Ajax框架
- 通用Ajax函数
- Ajax通用写法
- ajax 通用方法
- 一套通用Ajax框架
- extjs ajax 通用写法
- 一套通用Ajax框架 .
- Ajax通用代码封装
- 通用的Ajax格式
- 通用ajax分页
- gineGrid-通用ajax类(集成跨域访问).
- 基于通用分页类的Ajax异步实现
- 通用的AJAX基本功能源码
- ajax通用创建XMLHttpRequest对象
- 经典的SQL文sql
- WebService.htc文件应用
- java对excel文件的读写操作,这次是丰富的属性设置
- 金蝶实习(七)
- 检查密码和确认密码的JavaScript
- Ajax通用类
- Bmp图像数据结构
- apache2+php5+mysql5集成
- JMX架构的了解
- 查看服务器端目录和文件
- 从 MySQL 导入导出大量数据的程序实现方法
- js联动三级,四级菜单特效
- TOMCAT manager 出现403错误
- 鼠标放上列表后显示图片和描述效果