Home > Web Front-end > JS Tutorial > Tutorial on writing a simple AJAX method library in JavaScript

Tutorial on writing a simple AJAX method library in JavaScript

巴扎黑
Release: 2017-08-06 15:27:12
Original
1376 people have browsed it

This article mainly introduces in detail how to write a simple ajax method library in js. It has certain reference value. Interested friends can refer to it.

The examples in this article share with you how to write js The specific code of the ajax method library is for your reference. The specific content is as follows

Specific code


~function(){
  //ajax:实现ajax请求的公共方法;当一个方法传递的参数过多,而且还不固定,我们使用对象统一传值法(把需要传递的参数值都放在一个对象中,一起传递进去即可)
  function ajax(options){
    //把需要使用的参数值设定一个规则和初始值
    var _default = {
      url:"",//请求的地址
      type:"get",//请求的方式
      dataType:"json",//设置请求回来的内容格式
      async:true,//请求是同步还是异步
      data:null,//放在请求主体中的内容(POST)
      getHead:null,//当READY STATE===2的时候执行的回调方法
      success:null//当READY STATE===4的时候执行的回调方法
    };
    //使用用户自己传递进来的值覆盖我们的默认值
    for(var key in options){
      if(options.hasOwnProperty(key)){
        _default[key] = options[key];
      }
    }
    //如果当前的请求方式是get,我们需要在URL的末尾加随机数清楚缓存
    if(_default.type==="get"){
      _default.url.indexOf("?") >=0 ? _default.url += "&" : _default.url += "?";
      _default.url +="_="+Math.random();
    }
    //SEND AJAX
    var xhr = createXHR();
    xhr.open(_default.type,_default.url,_default.async);
    xhr.onreadystatechange = function(){
      if(/^2\d{2}/.test(xhr.status)){
        //想要在READY STATE等于2的时候做一些操作,需要保证AJAX是异步请求
        if(xhr.readyState === 2){
          if(typeof _default.getHead === "function"){
            _default.getHead.call(xhr);
          }
        }
        if(xhr.readyState === 4){
          var val = xhr.responseText;
          //如果传递的参数值是json,说明获取的内容应该是json格式的对象
          if(_default.dataType === "json"){
            val = "JSON" in window ? JSON.parse(val) : eval("("+val+")");
          }
          _default.success && _default.success.call(xhr,val)

        }
      }
    }
    xhr.send(_default.data);
  }
  window.ajax = ajax;
}()

ajax({
  url:"data.txt",
  type:"get",
  dataType:"json",
  async:false,
  getHead:function(){
    //this xhr当前AJAX对象
  },
  success:function(data){
    //this xhr当前AJAX对象
    //data:我们从服务器获取的主体内容
  }

})
Copy after login

The above is the detailed content of Tutorial on writing a simple AJAX method library in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template