Table of Contents
onreadystatechange analysis
Home Backend Development PHP Tutorial Detailed introduction to ajax simple packaging

Detailed introduction to ajax simple packaging

Jan 29, 2018 pm 03:09 PM
ajax introduce detailed

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions PyCharm Beginner's Guide: Comprehensive Analysis of Replacement Functions Feb 25, 2024 am 11:15 AM

PyCharm is a powerful Python integrated development environment with rich functions and tools that can greatly improve development efficiency. Among them, the replacement function is one of the functions frequently used in the development process, which can help developers quickly modify the code and improve the code quality. This article will introduce PyCharm's replacement function in detail, combined with specific code examples, to help novices better master and use this function. Introduction to the replacement function PyCharm's replacement function can help developers quickly replace specified text in the code

Detailed introduction of Samsung S24ai functions Detailed introduction of Samsung S24ai functions Jun 24, 2024 am 11:18 AM

2024 is the first year of AI mobile phones. More and more mobile phones integrate multiple AI functions. Empowered by AI smart technology, our mobile phones can be used more efficiently and conveniently. Recently, the Galaxy S24 series released at the beginning of the year has once again improved its generative AI experience. Let’s take a look at the detailed function introduction below. 1. Generative AI deeply empowers Samsung Galaxy S24 series, which is empowered by Galaxy AI and brings many intelligent applications. These functions are deeply integrated with Samsung One UI6.1, allowing users to have a convenient intelligent experience at any time, significantly improving the performance of mobile phones. Efficiency and convenience of use. The instant search function pioneered by the Galaxy S24 series is one of the highlights. Users only need to press and hold

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Introduction to the skills and attributes of Hua Yishan Heart of the Moon Lu Shu Introduction to the skills and attributes of Hua Yishan Heart of the Moon Lu Shu Mar 23, 2024 pm 05:30 PM

In Hua Yishan Heart Moon, Lu Shu is an SSR celebrity. He is positioned as a single-target backline player and has a very impressive critical hit rate. Many players don’t know much about Lu Shu. Here’s what I’ve brought you. Come and take a look at the introduction to the skills and attributes of Hua Yishan Heart of the Moon Lu Shu. Celebrity Attributes Celebrity Skills 1. Lu Ming Shuzhong Skill Description: Lu Shu was born in Qiongqihui in Shuzhong. He has practiced martial arts since he was a child and has outstanding martial arts skills. Causes basic attack damage equal to 100% of the enemy's back row attack power, and reduces the target's rage by 10 points. Skill attributes: Level 2: Basic attack damage increased to 105%. Level 2: Basic attack damage is increased to 110%, and the target's rage is reduced by 15 points. Level 2: Basic attack damage increased to 115%. Level 2: Basic attack damage is increased to 120%, and the target's rage is reduced by 20 points. Level 2: Basic attack

See all articles