jQuery的ajax方法的封装

一,前言:

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

  真正的核心就是这段代码:

var xhr = new XMLHTTPRequest();
xhr.open("method", "url", "async");
xhr.send(null);
xhr.onreadystatechange = function(){
    if(xhr.readystate == 4){
   if(xhr.status == 200){
     console.log(xhr.responseText)
   }
  }
}

  一个对象(XMLHTTPRequest对象)、

  两个方法(包括open("method", "url", "async")方法和send(content)方法)、

  三个属性(readystate表示当前请求状态,status表示http请求状态码,responseText表示服务器反馈内容),

  当然还有一个事件——onreadystatechange ,是在readystate状态改变时触发的事件。具体的内容请点击链接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)
    }
});  

二,结语:

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

猜你喜欢

转载自www.cnblogs.com/nangezi/p/9038839.html