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


    一,前言:

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

    Ajax工作原理和原生JS的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)
        }
    });  

    二,结语:

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

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

  • 相关阅读:
    MySQL 分组
    MySQL LIKE 子句
    MySQL DELETE 语句
    MySQL UPDATE 查询
    MySQL where 子句
    MySQL 插入数据
    MySQL 查询数据
    MySQL 删除数据表
    MySQL 创建数据表
    MySQL 数据类型
  • 原文地址:https://www.cnblogs.com/nangezi/p/9038839.html
Copyright © 2020-2023  润新知