码迷,mamicode.com
首页 > Web开发 > 详细

使用js手写兼容jquery的ajax

时间:2015-08-11 01:46:56      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

jquery-ajax.js

var $ = new function()
{
    this.ajax = function(param)
    {
        if(!param){return;}
        // compatible all new browsers and IE5 and IE6
        var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        if (xmlhttp == null) {alert("Your browser does not support XMLHTTP.");return;}
        var type = param[‘type‘] ? param[‘type‘] : ‘get‘;
        var url = param[‘url‘] ? param[‘url‘] : ‘#‘;
        var async = param[‘async‘] == false ? false : true;
        var data = param[‘data‘] ? param[‘data‘] : null;
        var dataType = param[‘dataType‘] ? param[‘dataType‘] : ‘html‘;
        var success = typeof param[‘success‘] == ‘function‘ ? param[‘success‘] : function(){};
        var error = typeof param[‘error‘] == ‘function‘ ? param[‘error‘] : function(){};
        var complete = typeof param[‘complete‘] == ‘function‘ ? param[‘complete‘] : function(){};
        var timeout = param[‘timeout‘] ? param[‘timeout‘] : 3000;
        try
        {
            xmlhttp.open(type,url,async);
            xmlhttp.send(data);
            xmlhttp.onreadystatechange = function()
            {
                if(xmlhttp.readyState != 4){return;}
                switch (xmlhttp.status)
                {
                    case 200 : success(xmlhttp.responseText);complete(xmlhttp,‘success‘);break;
                    case 404 : error(xmlhttp,‘Not Found‘,null);complete(xmlhttp,‘error‘);break;
                    case 500 : error(xmlhttp,‘Internal Server Error‘,null);complete(xmlhttp,‘error‘);break;
                    default : error(xmlhttp,‘error‘,null);complete(xmlhttp,‘error‘);break;
                }
            };
        }
        catch(e)
        {
            error(xmlhttp,‘error‘,e);
            complete(xmlhttp,‘error‘);
        }
    };
};



调用方法同jquery的ajax一样

$.ajax({
    url : ‘‘,
    type : ‘post‘,
    async : true,
    data : {data : data},
    success : function(data) {
        //do some thing
    }
});



使用js手写兼容jquery的ajax

标签:

原文地址:http://my.oschina.net/153/blog/490413

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!