09-06
23
23
简单实用的ajax函数
作者:mzoe 日期:2009-06-23 时间:20:07
收缩
用一些优秀的JavaScript框架(比如jquery)来实现ajax的效果是非常简单的事情,但是有时候我们并不需要太过绚丽的js特效,那么给页面引入一个相对庞大的JavaScript框架就显得太过奢侈浪费了。这里我根据jquery的调用形式写了个简单的ajax调用函数:
- var xmlHttp = null;
- function createXMLHttpRequest() {
- if (window.ActiveXObject) {
- 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'];
- for(var i = 0; i < versions.length; i++) {
- try {
- xmlHttp = new ActiveXObject(versions[i]);
- } catch(e) {}
- }
- } else if (window.XMLHttpRequest) {
- xmlHttp = new XMLHttpRequest();
- }
- }
- function $ajax(opt) {
- opt.asynchronous = opt.asynchronous || true;
- opt.cachecontrol = opt.cachecontrol || false;
- opt.method = (opt.method || 'post').toLowerCase();
- opt.pars = opt.pars || '';
- createXMLHttpRequest();
- xmlHttp.onreadystatechange = function() {
- if (xmlHttp.readyState == 4) {
- if (xmlHttp.status == 200) {
- if (opt.success) opt.success(xmlHttp.responseText);
- } else {
- alert("there is an error in server!the status is:" + xmlHttp.status.toString());
- }
- }
- }
- if (opt.method == "get") {
- if (!opt.cachecontrol) opt.pars += (opt.pars != "" ? '&' : '?') + "time=" + new Date().getTime();
- if (opt.pars != "") opt.url += "?" + opt.pars;
- xmlHttp.open("GET", opt.url, opt.asynchronous);
- xmlHttp.send(null);
- } else {
- if (!opt.cachecontrol) opt.url += "?time=" + new Date().getTime();
- xmlHttp.open("POST", opt.url, opt.asynchronous);
- xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- xmlHttp.send(opt.pars);
- }
- }
- function $get(url, callback) {
- $ajax({
- url: url,
- method: 'get',
- success: callback
- });
- }
- function $post(url, data, callback) {
- $ajax({
- url: url,
- method: 'post',
- pars: data,
- success: callback
- });
- }
调用方式:
- $get('/checkUserName/?userName=mzoe', function(str) {
- alert(str);
- });
- $post('/checkUserName/', 'userName=mzoe', function(str) {
- alert(str);
- });