• 原生js实现ajax方法


    下面是一个比较完整的Ajax

    function ajax(){ 
      var ajaxData = { 
        type:arguments[0].type || "GET", 
        url:arguments[0].url || "", 
        async:arguments[0].async || "true", 
        data:arguments[0].data || null, 
        dataType:arguments[0].dataType || "text", 
        contentType:arguments[0].contentType || "application/x-www-form-urlencoded", 
        beforeSend:arguments[0].beforeSend || function(){}, 
        success:arguments[0].success || function(){}, 
        error:arguments[0].error || function(){} 
      } 
      ajaxData.beforeSend() 
      var xhr = createxmlHttpRequest();  
      xhr.responseType=ajaxData.dataType; 
      xhr.open(ajaxData.type,ajaxData.url,ajaxData.async);  
      xhr.setRequestHeader("Content-Type",ajaxData.contentType);  
      xhr.send(convertData(ajaxData.data));  
      xhr.onreadystatechange = function() {  
        if (xhr.readyState == 4) {  
          if(xhr.status == 200){ 
            ajaxData.success(xhr.response) 
          }else{ 
            ajaxData.error() 
          }  
        } 
      }  
    } 
      
    function createxmlHttpRequest() {  
      if (window.ActiveXObject) {  
        return new ActiveXObject("Microsoft.XMLHTTP");  
      } else if (window.XMLHttpRequest) {  
        return new XMLHttpRequest();  
      }  
    } 
      
    function convertData(data){ 
      if( typeof data === 'object' ){ 
        var convertResult = "" ;  
        for(var c in data){  
          convertResult+= c + "=" + data[c] + "&";  
        }  
        convertResult=convertResult.substring(0,convertResult.length-1) 
        return convertResult; 
      }else{ 
        return data; 
      } 
    }

    对比看下Jquery的Ajax

    ajax({ 
      type:"POST", 
      url:"ajax.php", 
      dataType:"json", 
      data:{"val1":"abc","val2":123,"val3":"456"}, 
      beforeSend:function(){ 
        //some js code 
      }, 
      success:function(msg){ 
        console.log(msg) 
      }, 
      error:function(){ 
        console.log("error") 
      } 
    })
    ajax({ 
      type:"POST", 
      url:"ajax.php", 
      dataType:"json", 
      data:{"val1":"abc","val2":123,"val3":"456"}, 
      beforeSend:function(){ 
        //some js code 
      }, 
      success:function(msg){ 
        console.log(msg) 
      }, 
      error:function(){ 
        console.log("error") 
      } 
    })
  • 相关阅读:
    vmware安装ubuntu
    加快pip install的速度
    在Dataframe中寻找特定值所在行的行号
    后续:尝试交易策略
    小实验:股票涨幅日间的相关性
    大数据之数据预处理
    并查集
    2020华为杯数学建模B题-RON建模 赛后总结与分析
    二叉树的遍历总结
    几数之和分析,解法,优化和总结
  • 原文地址:https://www.cnblogs.com/adaia/p/7142598.html
Copyright © 2020-2023  润新知