在用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
- }