MZOE'S BLOG

mzoe的个人主页

Page 1 of 11
预览模式:普通 | 列表
09-06
23

简单实用的ajax函数

作者:mzoe 日期:2009-06-23 时间:20:07

收缩

  用一些优秀的JavaScript框架(比如jquery)来实现ajax的效果是非常简单的事情,但是有时候我们并不需要太过绚丽的js特效,那么给页面引入一个相对庞大的JavaScript框架就显得太过奢侈浪费了。这里我根据jquery的调用形式写了个简单的ajax调用函数:

  1. var xmlHttp = null;  
  2. function createXMLHttpRequest() {    
  3.     if (window.ActiveXObject) {  
  4.         var versions = ['Microsoft.XMLHTTP''MSXML.XMLHTTP''Microsoft.XMLHTTP''Msxml2.XMLHTTP.7.0''Msxml2.XMLHTTP.6.0''Msxml2.XMLHTTP.5.0''Msxml2.XMLHTTP.4.0''MSXML2.XMLHTTP.3.0''MSXML2.XMLHTTP'];  
  5.         for(var i = 0; i < versions.length; i++) {  
  6.             try {  
  7.                 xmlHttp = new ActiveXObject(versions[i]);  
  8.             } catch(e) {}  
  9.         }  
  10.     } else if (window.XMLHttpRequest) {  
  11.         xmlHttp = new XMLHttpRequest();  
  12.     }  
  13. }  
  14. function $ajax(opt) {  
  15.     opt.asynchronous = opt.asynchronous || true;  
  16.     opt.cachecontrol = opt.cachecontrol || false;  
  17.     opt.method = (opt.method || 'post').toLowerCase();  
  18.     opt.pars = opt.pars || '';  
  19.     createXMLHttpRequest();  
  20.     xmlHttp.onreadystatechange = function() {  
  21.         if (xmlHttp.readyState == 4) {  
  22.             if (xmlHttp.status == 200) {  
  23.                 if (opt.success) opt.success(xmlHttp.responseText);  
  24.             } else {  
  25.                 alert("there is an error in server!the status is:" + xmlHttp.status.toString());  
  26.             }  
  27.         }  
  28.     }  
  29.     if (opt.method == "get") {  
  30.         if (!opt.cachecontrol) opt.pars += (opt.pars != "" ? '&' : '?') + "time=" + new Date().getTime();  
  31.         if (opt.pars != "") opt.url += "?" + opt.pars;  
  32.         xmlHttp.open("GET", opt.url, opt.asynchronous);  
  33.         xmlHttp.send(null);  
  34.     } else {  
  35.         if (!opt.cachecontrol) opt.url += "?time=" + new Date().getTime();  
  36.         xmlHttp.open("POST", opt.url, opt.asynchronous);  
  37.         xmlHttp.setRequestHeader("Content-Type""application/x-www-form-urlencoded");  
  38.         xmlHttp.send(opt.pars);  
  39.     }  
  40. }  
  41. function $get(url, callback) {  
  42.     $ajax({  
  43.         url: url,  
  44.         method: 'get',  
  45.         success: callback  
  46.     });  
  47. }  
  48. function $post(url, data, callback) {  
  49.     $ajax({  
  50.         url: url,  
  51.         method: 'post',  
  52.         pars: data,  
  53.         success: callback  
  54.     });  

  调用方式:

  1. $get('/checkUserName/?userName=mzoe'function(str) {  
  2.     alert(str);  
  3. });  
  4.  
  5. $post('/checkUserName/''userName=mzoe'function(str) {  
  6.     alert(str);  
  7. }); 

 

Tags: ajax 函数

Page 1 of 11