Maison  >  Article  >  interface Web  >  Comment utiliser JS natif pour écrire un exemple de partage de code ajax (collection)

Comment utiliser JS natif pour écrire un exemple de partage de code ajax (collection)

黄舟
黄舟original
2017-05-31 10:17:521181parcourir

L'éditeur suivant vous apportera un exemple d'écriture ajax en utilisant js natif (recommandé). L'éditeur pense que c'est plutôt bien, alors je vais le partager avec vous maintenant et le donner comme référence. Suivons l'éditeur et jetons un coup d'œil

Les exemples sont les suivants :

// 使用原生js 封装ajax
// 兼容xhr对象
function createXHR(){
  if(typeof XMLHttpRequest != "undefined"){ // 非IE6浏览器
    return new XMLHttpRequest();
  }else if(typeof ActiveXObject != "undefined"){  // IE6浏览器
    var version = [
          "MSXML2.XMLHttp.6.0",
          "MSXML2.XMLHttp.3.0",
          "MSXML2.XMLHttp",
    ];
    for(var i = 0; i < version.length; i++){
      try{
        return new ActiveXObject(version[i]);
      }catch(e){
        //跳过
      }
    }
  }else{
    throw new Error("您的系统或浏览器不支持XHR对象!");
  }
}
// 转义字符
function params(data){
  var arr = [];
  for(var i in data){
    arr.push(encodeURIComponent(i) + "=" + encodeURIComponent(data[i]));
  }
  return arr.join("&");
}
// 封装ajax
function ga_ajax(obj){
  var xhr = createXHR();
  obj.url = obj.url + "?rand=" + Math.random(); // 清除缓存
  obj.data = params(obj.data);   // 转义字符串
  if(obj.method === "get"){   // 判断使用的是否是get方式发送
    obj.url += obj.url.indexOf("?") == "-1" ? "?" + obj.data : "&" + obj.data;
  }
  // 异步
  if(obj.async === true){
    // 异步的时候需要触发onreadystatechange事件
    xhr.onreadystatechange = function(){
      // 执行完成
      if(xhr.readyState == 4){
        callBack();
      }
    }
  }
  xhr.open(obj.method,obj.url,obj.async); // false是同步 true是异步 // "demo.php?rand="+Math.random()+"&name=ga&ga",
  if(obj.method === "post"){
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.send(obj.data);
  }else{
    xhr.send(null);
  }
  // xhr.abort(); // 取消异步请求
  // 同步
  if(obj.async === false){
    callBack();
  }
  // 返回数据
  function callBack(){
    // 判断是否返回正确
    if(xhr.status == 200){
      obj.success(xhr.responseText);
    }else{
      obj.Error("获取数据失败,错误代号为:"+xhr.status+"错误信息为:"+xhr.statusText);
    }
  }
}

var html = document.getElementsByTagName("html")[0];
html.onclick = function(){
  ga_ajax({
    "method" : "post",
    "url" : "demo.php",
    "data" : {
      "name" : "gao",
      "age" : 100,
      "num" : "12346&598"
    },
    "success" : function(data){
      alert(data);
    },
    "Error" : function(text){
      alert(text);
    },
    "async" : false
  });
}

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn