类似jQuery的原生JS封装的ajax方法

一,前言:

  前文,我们介绍了ajax的原理和核心内容,主要讲的是ajax从前端到后端的数据传递的整个过程。

Ajax工作原理

二,正文:

  先来看看jQuery中Ajax方法的使用:

$.ajax({
    type: "GET",              //访问服务器的方式,GET/POST
    url: "test.json",         //url表示访问的服务器地址
    data: {username: "",     
           content: ""},     //data表示传递到后台的数据,使用键值对形式传递
    async: true,              //true表示异步,false表示同步
    success: function(data){
        console.log(data)
    },
    error: function(err){
        console.log(err)
    }
});            

  

  那么我们想要封装成类似JQuery的形式,供调用,怎么办呢?

function $Ajax(opt){
    opt = opt || {};
    opt.type = opt.type || "post";
    opt.url = opt.url || "";
    opt.async = opt.async || true;
    opt.data = opt.data || null;

    opt.success = opt.success || function(){};
    opt.error = opt.error || function(){};
      
    var xhr = new XMLHTTPRequest();
    var params = {};
    for(var key in opt.data){
         params.push(key + "=" + opt.data[key]);
    }
    var sendData = params.join("&");
    if(opt.type.toUpperCase() == "GET"){
         xhr.open(opt.type, opt.url + "?" + sendData, opt.async);
         xhr.send(null);
    }else{
         xhr.open(opt.type, opt.url, opt.async);
         xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
         xhr.send(sendData);
    }

    xhr.onreadystatechange = function(){
         if(xhr.readystate == 4){
              if(xhr.status == 200){
                    opt.success && opt.success(xhr.responseText);  
              }else{
                    opt.error && xhr.error(xhr.status);
              }
         }
    }
}                  

  

  已经封装好了,接下来就是调用了,就像jQuery那样使用就行:

$Ajax({
    type: "GET",     
    url: "test.json", 
    data: {username: "", content: ""}, 
    async: true,
    success: function(responseText){
        console.log(responseText)
    },
    error: function(status){
        console.log(status)
    }
});  

二,结语:

  已经很晚了,没有进行测试,也没有详细进行注释,有时间再完善吧。

详细看这一篇:Ajax工作原理和原生JS的ajax封装