Home > Backend Development > PHP Tutorial > Detailed introduction to ajax simple packaging

Detailed introduction to ajax simple packaging

小云云
Release: 2023-03-19 18:02:02
Original
1625 people have browsed it

This article mainly shares with you the detailed introduction of ajax simple encapsulation, hoping to help everyone.

ajax is generally divided into four simple parts:

  1. Create an ajax object (if it is compatible with IE, you need to do some processing)

  2. Connection, that is, the open method of the request object (get and post are slightly different, the get parameter must be placed after the url, and the request header must be set for post)

  3. Send, that is, the send of the request object Function (the post parameter is placed in send)

  4. is received and processed in the onreadystatechange (storage function or function name. Whenever the readyState attribute changes, the function will be called.) function .

You can also add timeouts.

onreadystatechange analysis

  1. You must first determine the status of readyState (there are four states)

    ①: 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

  2. When readyState is equal to 4, you have to judge the status of status

  3. When the request is successful, the status status is 200-302, and there is 304 (caching)

'use strict';

var $ = {};
$.ajax = ajax;

function ajax(options) {

  // 解析参数
  options = options || {};
  if (!options.url) return;
  options.type = options.type || 'get';
  options.timeout = options.timeout || 0;

  // 1 创建ajax
  if (window.XMLHttpRequest) {

    // 高级浏览器和ie7以上
    var xhr = new XMLHttpRequest();
  } else {

    //ie6,7,8
    var xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
  }

  // 2 连接
  var str = jsonToUrl(options.data);
  if (options.type === 'get') {
    xhr.open('get', `${options.url}?${str}`, true);

    // 3 发送
    xhr.send();
  } else {
    xhr.open('post', options.url, true);

    // 请求头
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

    // 3 发送
    xhr.send();
  }

  // 接收
  xhr.onreadystatechange = function() {

    // 完成
    if (xhr.readyState === 4) {

      // 清除定时器
      clearTimeout(timer);

      if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {

        // 成功
        options.success && options.success(xhr.responseText);
      } else {
        options.error && options.error( xhr.status );
      }
    }
  };

  
  // 超时
  if (options.timeout) {
    var timer = setTimeout(function(){ 
            alert("超时了");
            xhr.abort(); // 终止
        },options.timeout);
  }
}


// json转url
function jsonToUrl(json) {
  var arr = [];
  json.t = Math.random();
  for(var name in json) {
    arr.push(name + '=' + encodeURIComponent(json[name]));
  }
  return arr.join('&');
}
Copy after login

Related recommendations:

WeChat applet implements a code example of simple encapsulation of network requests

php simply encapsulates some common JS operations_PHP tutorial

Simple ajax packaging


The above is the detailed content of Detailed introduction to ajax simple packaging. 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