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)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

'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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
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.

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

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:

What is Dogecoin What is Dogecoin Apr 01, 2024 pm 04:46 PM

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

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

Introduction to the online score checking platform (convenient and fast score query tool) Introduction to the online score checking platform (convenient and fast score query tool) Apr 30, 2024 pm 08:19 PM

A fast score query tool provides students and parents with more convenience. With the development of the Internet, more and more educational institutions and schools have begun to provide online score check services. To allow you to easily keep track of your child's academic progress, this article will introduce several commonly used online score checking platforms. 1. Convenience - Parents can check their children's test scores anytime and anywhere through the online score checking platform. Parents can conveniently check their children's test scores at any time by logging in to the corresponding online score checking platform on a computer or mobile phone. As long as there is an Internet connection, whether at work or when going out, parents can keep abreast of their children's learning status and provide targeted guidance and help to their children. 2. Multiple functions - in addition to score query, it also provides information such as course schedules and exam arrangements. Many online searches are available.

See all articles