Home > Web Front-end > JS Tutorial > A brief introduction to writing ajax by yourself without using a library (framework)

A brief introduction to writing ajax by yourself without using a library (framework)

亚连
Release: 2018-05-24 16:32:22
Original
1629 people have browsed it

This article introduces to you how to write ajax without a library (framework). Friends who are interested can learn together.

Usually, ajax is used to request data and load a library (framework). Maybe just maybe. Used the ajax part of it.

Write ajax. Firstly, you can experience the process of solving problems and improve your technical skills. Secondly, sometimes you really don’t need such a large library (framework) at work. Why not write it yourself? Why.

Let’s first take a look at how the popular jQuery calls ajax

$.ajax({
  url:    'test.php',   //发送请求的URL字符串
  type:    'GET',     //发送方式 
  dataType:  'json',     //预期服务器返回的数据类型 xml, html, text, json, jsonp, script
  data:    'k=v&k=v',   //发送的数据 
  async:   true,      //异步请求 
  cache:   false,     //缓存 
  timeout:  5000,      //超时时间 毫秒
  beforeSend: function(){},  //请求之前
  error:   function(){},  //请求出错时
  success:  function(){},  //请求成功时
  complete:  function(){}  //请求完成之后(不论成功或失败)
});
Copy after login

Is such a call very comfortable and convenient? If you feel comfortable Then you can also refer to this design method when writing it yourself. It doesn't need to be too complicated, just meet your needs.

First understand the basic knowledge of ajax

XMLHttpRequest object

The XMLHttpRequest object is the core of ajax. It sends asynchronous requests to the server through the XMLHttpRequest object. The server gets the data and all modern browsers (IE7, Firefox, Chrome, Safari, Opera) support the XMLHttpRequest object (IE5 and IE6 use ActiveXObject).

 Create a compatible XMLHttpRequest object

var xhr = window.XMLHttpRequest? new XMLHttpRequest(): new ActiveXObject('Microsoft.XMLHTTP');

 Send a request to the server

xhr.open(method,url,async);
//method: type of request; GET or POST
//url: Requested URL
//async: true (asynchronous) or false (synchronous)
xhr.send(string);
//Send the request to the server
//string: only for POST Request
//GET is simpler and faster than POST request, and can be used in most cases
//In the following situations, please use POST request:
//Cache files cannot be used (Update files or databases on the server)
//Send a large amount of data to the server (POST has no data limit)
//POST is more stable and reliable than GET when sending user input containing unknown characters

 Server response

Use the responseText or responseXML attribute of the XMLHttpRequest object to obtain the response from the server.

If the response from the server is XML and needs to be parsed as an XML object, use the responseXML attribute.

If the response from the server is not XML, use the responseText property, which returns the response as a string.

 onreadystatechange event

When a request is sent to the server, we need to perform some response-based tasks. Whenever readyState changes, the onreadystatechange event is triggered. The readyState attribute stores the status information of XMLHttpRequest.

  Three important attributes of the XMLHttpRequest object:

  onreadystatechange //Storage function (or function name), Whenever the readyState attribute changes, this function will be called

  readyState //The state of the XMLHttpRequest is stored, changing from 0 to 4

0: The request is not initialized
1: The server connection has been established
2: The request has been received
3: The request is being processed
4: The request has been completed and the response is ready

   status  //200: "OK", 404: Page not found

 In the onreadystatechange event, we stipulate that when the server response is ready, it will be processed Tasks performed during preparation. When readyState is equal to 4 and status is 200, it means that the response is ready.

xhr.onreadystatechange = function(){
  if( xhr.readyState == 4 && xhr.status == 200 ){
    //准备就绪 可以处理返回的 xhr.responseText 或者 xhr.responseXML 
  }
};
Copy after login


A simple ajax request is as follows:

var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.onreadystatechange = function(){
  if( xhr.readyState == 4 && xhr.status == 200 ){
    //准备就绪 可以处理返回的 xhr.responseText 或者 xhr.responseXML 
  }
};
xhr.open(method,url,async);
xhr.send(string);
Copy after login


Supplement: 1. When sending a GET request, you may get cached results. To avoid this, you can add a unique ID and timestamp to the URL. 2. If you need to POST data like an HTML form, use setRequestHeader() to add HTTP headers. Then send the data in the send() method.

url += (url.indexOf(&#39;?&#39;) < 0 ? &#39;?&#39; : &#39;&&#39;) + &#39;_=&#39;+ (+new Date());
xhr.setRequestHeader(&#39;Content-type&#39;, &#39;application/x-www-form-urlencoded&#39;);
Copy after login


 Start writing your own ajax

Write a basic one first , define various parameter options, for reference

var $ = (function(){
  //辅助函数 序列化参数 
  function param(data){
    //..  
  }
 
  function ajax(opts){
    var _opts = {
      url    : &#39;/&#39;,       //发送请求URL地址
      type    : &#39;GET&#39;,      //发送请求的方式 GET(默认), POST
      dataType  : &#39;&#39;,        //预期服务器返回的数据类型 xml, html, text, json, jsonp, script
      data    : null,       //发送的数据 &#39;key=value&key=value&#39;, {key:value,key:value}  
      async   : true,       //异步请求 ture(默认异步), false
      cache   : true,       //缓存 ture(默认缓存), false 
      timeout  : 5,        //超时时间 默认5秒
      load    : function(){},   //请求加载中
      error   : function(){},   //请求出错时
      success  : function(){},   //请求成功时
      complete  : function(){}   //请求完成之后(不论成功或失败)
    }, aborted = false, key,
    xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject(&#39;Microsoft.XMLHTTP&#39;);
    for(key in opts) _opts[key] = opts[key];        
     
    /*
    if(_opts.dataType.toLowerCase() === &#39;script&#39;){
      //..
    }
    if(_opts.dataType.toLowerCase() === &#39;jsonp&#39;){
      //..
    }
    */
    if(_opts.type.toUpperCase() === &#39;GET&#39;){
      if(param(_opts.data) !== &#39;&#39;){
        _opts.url += (_opts.url.indexOf(&#39;?&#39;) < 0 ? &#39;?&#39; : &#39;&&#39;) + param(_opts.data);
      }
      !_opts.cache && ( _opts.url += (_opts.url.indexOf(&#39;?&#39;) < 0 ? &#39;?&#39; : &#39;&&#39;) + &#39;_=&#39;+(+new Date()) );
    }
 
    function checkTimeout(){
      if(xhr.readyState !== 4){
        aborted = true;
        xhr.abort();
      }
    }
    setTimeout(checkTimeout, _opts.timeout*1000);
     
    xhr.onreadystatechange = function(){
      if( xhr.readyState !== 4 ) _opts.load && _opts.load(xhr);
      if( xhr.readyState === 4 ){
        var s = xhr.status, xhrdata;
        if( !aborted && ((s >= 200 && s < 300) || s === 304) ){
          switch(_opts.dataType.toLowerCase()){
            case &#39;xml&#39;:
              xhrdata = xhr.responseXML;
            break;
            case &#39;json&#39;:
              xhrdata = window.JSON && window.JSON.parse ? JSON.parse(xhr.responseText) : eval(&#39;(&#39; + xhr.responseText + &#39;)&#39;);
            break;
            default:
              xhrdata = xhr.responseText;
          }
          _opts.success && _opts.success(xhrdata,xhr);
        }else{
          _opts.error && _opts.error(xhr);
        }
        _opts.complete && _opts.complete(xhr);
      }
    };   
    xhr.open(_opts.type,_opts.url,_opts.async);
    if(_opts.type.toUpperCase() === &#39;POST&#39;){
      xhr.setRequestHeader(&#39;Content-type&#39;, &#39;application/x-www-form-urlencoded&#39;);
    }
    xhr.send(_opts.type.toUpperCase() === &#39;GET&#39; ? null : param(_opts.data));
  }
  return {
    ajax: ajax
  }
})();
Copy after login

After defining the parameter options, let’s analyze it. Among them, dataType is the focus of the entire ajax, and it determines whether the code is simple or complex.

Here dataType is the data type expected to be returned by the server: xml, html, text, json, jsonp, script

1. When it is xml, the response from the server is XML, use the responseXML attribute Get the returned data

 2. When it is html, text, or json, use the responseText attribute to get the returned data

      a. 为html时,返回纯文本HTML信息,其中包含的script标签是否要在插入dom时执行 ( 代码复杂度+3 )

      b. 为json时, 返回JSON数据,要安全、要便捷、要兼容 ( 代码复杂度+2 )

  3. 为jsonp时,一般跨域才用它,不用原来的ajax请求了,用创建script法( 代码复杂度+2 )

  4. 为script时: 要跨域时,不用原来的ajax请求了,用创建script法( 代码复杂度+1 ); 不跨域,返回纯文本JavaScript代码, 使用 responseText 属性获取返回的数据 ( 代码复杂度+1 )

  其中,在html片段中的script标签、jsonp、script,都要用到创建script标签的方式。

  处理dataType为json

xhrdata = window.JSON && window.JSON.parse ? JSON.parse(xhr.responseText) : eval('(' + xhr.responseText + ')');

  这是最简单的处理方式了,要JSON兼容,可以用json2.js。

  处理dataType为jsonp

  jsonp是要通过script标签来请求跨域的,先了解下流程:

  这上图中 a.html中请求了 http://www.b.com/b.php?callback=add (在ajax程序中请求url就是这个链接),在b.php中读取了传过来的参数 callback=add 根据获取到的参数值(值为add),以JS语法生成了函数名,并把json数据作为参数传入了这个函数,返回以JS语法生成的文档给a.html,a.html解析并执行返回的JS文档,调用了定义好的add函数。

  在程序中一般采用更通用的方式去调用,比如下面这个广泛使用的loadJS函数:

function loadJS(url, callback) {
  var doc = document, script = doc.createElement(&#39;script&#39;), body = doc.getElementsByTagName(&#39;body&#39;)[0];
  script.type = &#39;text/javascript&#39;;
  if (script.readyState) { 
    script.onreadystatechange = function() {
      if (script.readyState == &#39;loaded&#39; || script.readyState == &#39;complete&#39;) {
        script.onreadystatechange = null;
        callback && callback();
      }
    };
  } else { 
    script.onload = function() {
      callback && callback();
    };
  }
  script.src = url;
  body.appendChild(script);
}
Copy after login

  这样把请求的url,传入loadJS函数,得到一样的结果。

loadJS('http://www.b.com/b.php?callback=add');

  因为是动态创建script,请求成功返回,JS代码就立即执行,如果请求失败是没有任何提示的。因此自定义的参数选项: _opts.success 能调用,_opts.error不能调用。

  ajax处理jsonp也有两种情况:

  1. 设置了请求URL后的参数 callback=add 特别是定义了函数名add,请求成功返回,JS代码就立即执行(这里就是调用 add({"a":8,"b":2}) )

  2. 在_opts.success中处理JSON数据,就是请求成功返回,JS代码不执行,并把函数中的参数挪出来,作为_opts.success的参数返回( 这里相当于处理字符串 'add({"a":8,"b":2})' ,去掉 'add(' 和 ‘)',得到 {"a":8,"b":2} )

  处理dataType为html

  如果不处理HTML片段中script标签,直接把responseText返回值插入DOM树就可以了。如果要处理script,就要把HTML片段中的script标签找出来,对买个script单独处理,并注意是script标签中包含的JS代码还是通过src请求的。

  处理dataType为script

  如果要跨域时,用创建script的方式,和处理jsonp类似; 不跨域,使用 responseText 属性获取返回的数据,可以用 eval 来让代码执行,也可以创建script来执行。

function addJS(text) {
  var doc = document, script = doc.createElement(&#39;script&#39;), head = doc.getElementsByTagName(&#39;body&#39;)[0];
  script.type = &#39;text/javascript&#39;;
  script.text = text;
  body.appendChild(script);
}
Copy after login

  到此ajax差不多分析完了,根据实际需要,添加各种功能,去思考每种功能是怎样实现的,并能找到解决方法。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

MVC中基于Ajax和HTML5实现文件上传功能

jquery与php结合实现AJAX长轮询

初步了解JavaScript,Ajax,jQuery,并比较三者关系

The above is the detailed content of A brief introduction to writing ajax by yourself without using a library (framework). 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