Home Web Front-end JS Tutorial Five years of experience in using Ajax

Five years of experience in using Ajax

Apr 24, 2018 pm 04:25 PM
ajax use

This time I will bring you the summary experience of using Ajax for 5 years. What are the precautions when using Ajax? The following is a practical case, let’s take a look.

1. Introduction to Ajax, advantages and disadvantages, application scenarios and technologies

Introduction to Ajax:

Asynchronous Javascript And XML (Asynchronous JavaScript and XML)

It is not a single technology, but a combination of organically utilizing a series of technologies related to interactive web applications

AJAX is a technology for creating fast, dynamic web pages. AJAX enables web pages to update asynchronously by exchanging small amounts of data with the server in the background. This means that parts of a web page can be updated without reloading the entire page.

Advantages:

  1. No page refresh, good user experience.

  2. Asynchronous communication, faster response capability.

  3. Reduce redundant requests and reduce server burden

  4. Based on standardized and widely supported technology, no need to download plug-ins or applets

Disadvantages:

  1. ajax kills the back button, which is the browser back mechanism of destruction.

  2. There are certain security issues.

  3. The support for search engines is relatively weak.

  4. Destroys the exception mechanism of the program.

  5. Unable to access directly using URL

ajax application scenario

  • Scenario 1. Data verification

  • Scenario 2. Fetch data on demand

  • Scenario 3. Automatically update the page

AJAX contains the following five parts:

ajax is not a new technology, but several original technologies combination. It is composed of the following technologies.

  1. Represented using CSS and XHTML.

  2. Use the DOM model for interaction and dynamic display.

  3. Data exchange and operation technology, using XML and XSLT

  4. Use XMLHttpRequest to communicate asynchronously with the server.

  5. Use javascript to bind and call.

Among the above technologies, except for the XmlHttpRequest object, all other technologies are based on web standards and have been widely used. Although XMLHttpRequest has not yet been adopted by W3C , but it is already a de facto standard, because almost all major browsers currently support it

The first picture especially illustrates the structure and structure of traditional Web applications. The structural difference between Web applications using AJAX technology

The main difference is actually not JavaScript, not HTML/XHTML and CSS, but the use of XMLHttpRequest to asynchronously request XML data from the server

Let’s look at the second picture again. In the traditional Web application model, the user experience is fragmented. Click ->wait->see the new page->click again ->Wait some more. After adopting AJAX technology, most of the calculation work is completed by the server without the user noticing.

2. Steps to create ajax

The principle of Ajax is simply to send an asynchronous request to the server through the XmlHttpRequest object, obtain data from the server, and then use javascript to operate the DOM and update the page. The most critical step in this is to obtain the request data from the server. Creating ajax natively can be divided into the following four steps

1. Create an XMLHttpRequest object

The core of Ajax is the XMLHttpRequest object, which is implemented by Ajax The key is to send asynchronous requests, receive responses and execute callbacks through it.

All modern browsers (IE7, Firefox, Chrome, Safari and Opera) have built-in XMLHttpRequest objects.

Syntax for creating XMLHttpRequest objects:

var xhr = new XMLHttpRequest();
Copy after login

Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:

var xhr = new ActiveXObject("Microsoft.XMLHTTP");
Copy after login

To cope with all modern browsers, including IE5 and IE6, please check whether the browser supports the XMLHttpRequest object. If supported, an XMLHttpRequest object is created. If it is not supported, create an ActiveXObject:

Compatible with each browser's tool function for creating Ajax

function createRequest (){
 try {
 xhr = new XMLHttpRequest();
 }catch (tryMS){
 try {
 xhr = new ActiveXObject("Msxm12.XMLHTTP");
 } catch (otherMS) {
 try {
 xhr = new ActiveXObject("Microsoft.XMLHTTP");
 }catch (failed) {
 xhr = null;
 }
 }
 }
 return xhr;
}
Copy after login

2. Prepare the request

Initialize the XMLHttpRequest object and accept three parameters:

xhr.open(method,url,async);
Copy after login

The first parameter represents a string of request type, its value can be GET or POST .

GET request:

xhr.open("GET",demo.php?name=tsrot&age=24,true);
Copy after login

POST request:

xhr.open("POST",demo.php,true);
Copy after login

The second parameter is the URL to which the request is to be sent. .

The third parameter is true or false, indicating whether the request is issued in asynchronous or synchronous mode. (The default is true, false is generally not recommended)

  • false: Requests issued in synchronous mode will suspend the execution of all javascript code until the server gets a response. If the browser is connected to the network When there is a problem or when downloading the file, the page will hang all the time.

  • true: For requests issued in asynchronous mode, while the request object is sending and receiving data, the browser can continue to load the page and execute other javascript codes

3. Send a request

xhr.send();
Copy after login

Generally, the parameters submitted using Ajax are mostly simple strings. You can directly use the GET method to write the parameters to be submitted. to the url parameter of the open method. At this time, the parameter of the send method is null or empty.

GET request:

xhr.open("GET",demo.php?name=tsrot&age=24,true);
xhr.send(null);
Copy after login

POST request:

If you need to POST data like an HTML form, please use setRequestHeader()To add HTTP header. Then specify the data you want to send in the send() method:

xhr.open("POST",demo.php,true);
xhr.setRequestHeder("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xhr.sen
Copy after login

4. Processing the response

xhr.onreadystatechange = function(){
 if(xhr.readyState == 4 && xhr.status == 200){
 console.log(xhr.responseText);
 }
}
Copy after login

onreadystatechange: Execute the following function when the processing process changes

readyState: Ajax processing process

0: The request is not initialized (open( has not been called yet) ) ).

1: The request has been established, but has not been sent (send() has not been called yet).

2: The request has been sent and is being processed (usually the content header can be obtained from the response now).

3: The request is being processed; usually some data is available in the response, but the server has not yet completed generating the response.

4: The response is complete; you can get and use the server's response.

status attribute:

  • 200: "OK"

  • 404: Page not found

responseText: Get response data in string form

responseXML: Get response data in XML form

The object is converted to JSON format using JSON .stringify

Convert json to object format using JSON.parse()

The return value is generally a json string, you can use JSON.parse (xhr.responseText)Convert to JSON object

从服务器传回的数据是json格式,这里做一个例子说明,如何利用

1、首先需要从XMLHttpRequest对象取回数据这是一个JSON串,把它转换为真正的JavaScript对象。使用JSON.parse(xhr.responseText)转化为JSON对象

2、遍历得到的数组,向DOM中添加新元素

function example(responseText){
var salep= document.getElementById("sales");
var sales = JSON.parse(responseText);
 for(var i=0;i<sales.length;i++){
 var sale = sales[i];
 var p = document.createElement("p");
 p.setAttribute("class","salseItem");
 p.innerHTML = sale.name + sale.sales;
 salsep.appendChild(p);
 }
}
Copy after login

5、完整例子

var xhr = false;
 if(XMLHttpRequest){
 xhr = new XMLHttpRequest();
 }else{
 xhr = new ActiveXObject("Microsoft.XMLHTTP");
};
if(xhr) {//如果xhr创建失败,还是原来的false
 xhr.open("GET","./data.json",true);
 xhr.send();
 xhr.onreadystatechange = function(){
 if(xhr.readyState == 4 && xhr.status == 200){
 console.log(JSON.parse(xhr.responseText).name);
 }
 }
}
Copy after login

data.json

{
 "name":"tsrot",
 "age":24
}
Copy after login

这个过程是一定要记在脑子里的

function ajax(url, success, fail){
 // 1. 创建连接
 var xhr = null;
 xhr = new XMLHttpRequest()
 // 2. 连接服务器
 xhr.open(&#39;get&#39;, url, true)
 // 3. 发送请求
 xhr.send(null);
 // 4. 接受请求
 xhr.onreadystatechange = function(){
 if(xhr.readyState == 4){
 if(xhr.status == 200){
 success(xhr.responseText);
 } else { // fail
 fail && fail(xhr.status);
 }
 }
 }
}
Copy after login

XMLHttpRequest 在异步请求远程数据时的工作流程

谈谈JSONP

要访问web服务器的数据除了XMLHttpRequest外还有一种方法是JSONP

如果HTML和JavaScript与数据同时在同一个机器上,就可以使用XMLHttpRequest

什么是JSONP?

JSONP(JSON with Padding)是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)

JSONP有什么用?

由于同源策略的限制,XmlHttpRequest只允许请求当前源(域名、协议、端口)的资源,为了实现跨域请求,可以通过script标签实现跨域请求,然后在服务端输出JSON数据并执行回调函数,从而解决了跨域的数据请求

如何使用JSONP?

在客户端声明回调函数之后,客户端通过script标签向服务器跨域请求数据,然后服务端返回相应的数据并动态执行回调函数
用XMLHttpRequest时,我们得到一个字符串;要用JSON.parse把字符串转化成对象,使用jsonp时,script标志会解析并执行返回的代码,等我们处理数据时,已经是一个JavaScript对象了

简单实例

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> 
<script type="text/javascript"> 
 function jsonpCallback(result) { 
 alert(result.a); 
 alert(result.b); 
 alert(result.c); 
 for(var i in result) { 
 alert(i+":"+result[i]);//循环输出a:1,b:2,etc. 
 } 
 } 
</script> 
<script type="text/javascript" src="http://crossdomain.com/services.php?callback=jsonpCallback"></script> 
<!--callback参数指示生成JavaScript代码时要使用的函数jsonpcallback-->
Copy after login

注意浏览器的缓存问题

  • 在末尾增加一个随机数可避免频繁请求同一个链接出现的缓存问题

  • `

三、 jQuery中的Ajax

jQuery中的ajax封装案例

//ajax请求后台数据
var btn = document.getElementsByTagName("input")[0];
btn.onclick = function(){
 
 ajax({//json格式
 type:"post",
 url:"post.php",
 data:"username=poetries&pwd=123456",
 asyn:true,
 success:function(data){
 document.write(data);
 }
 });
}
//封装ajax
function ajax(aJson){
 var ajx = null;
 var type = aJson.type || "get";
 var asyn = aJson.asyn || true;
 var url = aJson.url; // url 接收 传输位置
 var success = aJson.success;// success 接收 传输完成后的回调函数
 var data = aJson.data || '';// data 接收需要附带传输的数据
 
 if(window.XMLHttpRequest){//兼容处理
 ajx = new XMLHttpRequest();//一般浏览器
 }else
 {
 ajx = new ActiveXObject("Microsoft.XMLHTTP");//IE6+
 }
 if (type == "get" && data)
 {
 url +="/?"+data+"&"+Math.random();
 }
 
 //初始化ajax请求
 ajx.open( type , url , asyn );
 //规定传输数据的格式
 ajx.setRequestHeader('content-type','application/x-www-form-urlencoded');
 //发送ajax请求(包括post数据的传输)
 type == "get" ?ajx.send():ajx.send(aJson.data);
 
 //处理请求
 ajx.onreadystatechange = function(aJson){
 
 if(ajx.readState == 4){
 
 if (ajx.status == 200 && ajx.status<300)//200是HTTP 请求成功的状态码
 {
 //请求成功处理数据
 success && success(ajx.responseText);
 }else{
 alert("请求出错"+ajx.status);
 
 }
 }
 
 }
Copy after login

jQuery中的Ajax的一些方法

jquery对Ajax操作进行了封装,在jquery中的$.ajax()方法属于最底层的方法,第2层是load()$.get()$.post();第3层是$.getScript()$.getJSON() ,第2层使用频率很高

load()方法

load()方法是jquery中最简单和常用的ajax方法,能载入远程HTML代码并插入DOM中 结构为:load(url,[data],[callback])

使用url参数指定选择符可以加载页面内的某些元素 load方法中url语法:url selector 注意:url和选择器之间有一个空格

传递方式

load()方法的传递方式根据参数data来自动指定,如果没有参数传递,则采用GET方式传递,反之,采用POST

回调参数

必须在加载完成后才执行的操作,该函数有三个参数 分别代表请求返回的内容、请求状态、XMLHttpRequest对象
只要请求完成,回调函数就会被触发

$("#testTest").load("test.html",function(responseText,textStatus,XMLHttpRequest){
 //respnoseText 请求返回的内容
 //textStatus 请求状态 :sucess、error、notmodified、timeout
 //XMLHttpRequest 
})
Copy after login

load方法参数

Parameter name Type Description
url String Request the URL address of the HTML page
data(optional) Object Sent to the server key / value data
callback(optional) Function Callback function when the request is completed, whether the request is successful or failed

$.get() and $.post() methods

load() method is usually used to read from Get static data files from the web server. If you need to pass some parameters to the page in the server in the project, you can use $.get() and $.post() or $.ajax()Method

Note: The $.get() and $.post() methods are in jquery Global function

$.get() method

$.get()method uses GET method to make asynchronous requests

The structure is: $.get(url,[data],callback,type)

If the content format returned by the server is an xml document, the Content-Type type code needs to be set on the server side As follows: header("Content-Type:text/xml:charset=utf-8") //php

$.get() method parameter analysis

Parameters Type Description
url String The address of the requested HTML page
data(optional) Object Sent to the server The key/value data will be appended to the request URL as QueryString
callback (optional) Function Callback function for successful loading (only This method is called only when the return status of the Response is success)
type (optional) String The format of the content returned by the server, including xml , html, script, json, text and _default

$.post() method

It has the same structure and usage as the $.get() method, with the following differences

  • The GET request will pass the parameters followed by Zhang Nai's URL, while the POST request will be sent to the web server as the entity content of the Http message. In the ajax request, this difference is invisible to the user

  • The GET method has a size limit on the transmitted data (usually no larger than 2KB), while the amount of data transmitted using the POST method is much larger than the GET method (theoretically not limited)

  • The data requested by GET method will be cached by the browser, so others can read the data from the browser's history, such as account number and password. In some cases, the GET method will bring serious security problems, while POST can relatively avoid these problems.

  • The data passed by the GET and POST methods cannot be obtained on the server side. same. In PHP, use $_GET[] for GET method; use $_POST[] for POST method; both methods can be used for $_REQUEST[] Get

Summary

Use load(), $.get() and # The ##$.post() method completes some conventional Ajax programs. If you need complex Ajax programs, you need to use $.ajax()method

$.ajax() method

$.ajax() method is the lowest level Ajax implementation of jquery, its structure is $.ajax(options)

This method has only one parameter, but this object contains the request settings and callback functions required by the

$.ajax() method. The parameters are key / value Exists, all parameters are optional

$.ajax() method common parameter analysis

ParametersTypeDescription##urltypetimeoutdataType xml: Returns an XML document, which can be processed with jquerybeforeSend Function(XMLHttpRequest){complete Parameters: XMLHttpRequest object and a string describing the successful request typesuccess (1) Data returned by the server and processed according to the dataType parametererrorglobal

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

JQuery calls Ajax to load images

Detailed analysis of Ajax usage skills in JS

String (Default is the current page address)Send Requested address
String The request method (POST or GET) defaults to GET
Number Set request timeout (milliseconds)
String Expected server The type returned. The available types are as follows html: Returns plain text HTML information, and the included script tag will also be executed when inserted into the DOM
Script: Returns plain text javascript code. Results are not automatically cached unless the cache parameter is set. Note: When making remote requests, all POST requests will be converted to GET requests
json: Return JSON data
jsonp: JSONP format, when calling a function using jsonp format, for example: myurl?call back=?, jquery will automatically replace the latter one? is the correct function name to execute the callback function
text: Returns a plain text string

Function A function that can modify the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If false is returned in beforeSend, this Ajax request can be canceled. The XMLHttpRequest object is the only parameter This;//The options parameters passed when calling this Ajax request
}

Function Callback function after the request is completed (called when the request succeeds or fails) Function(XMLHttpRequest,textStatus){
This;//The options parameters passed when calling this Ajax request
}

Function The callback function called after a successful request has two parameters (2) A string describing the status
Function(data,textStatus){
//data may be xmlDoc, ``jsonObj, html, text, etc.
This;//The options parameters passed when calling this Ajax request
}

Function Function called when the request fails
Boolean Default is true. Indicates whether to trigger the global Ajax event. If set to false, it will not be triggered. AjaxStart or AjaxStop can be used to control various Ajax events

The above is the detailed content of Five years of experience in using Ajax. 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)

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

How to use Xiaoai Speaker How to connect Xiaoai Speaker to mobile phone How to use Xiaoai Speaker How to connect Xiaoai Speaker to mobile phone Feb 22, 2024 pm 05:19 PM

After long pressing the play button of the speaker, connect to wifi in the software and you can use it. Tutorial Applicable Model: Xiaomi 12 System: EMUI11.0 Version: Xiaoai Classmate 2.4.21 Analysis 1 First find the play button of the speaker, and press and hold to enter the network distribution mode. 2 Log in to your Xiaomi account in the Xiaoai Speaker software on your phone and click to add a new Xiaoai Speaker. 3. After entering the name and password of the wifi, you can call Xiao Ai to use it. Supplement: What functions does Xiaoai Speaker have? 1 Xiaoai Speaker has system functions, social functions, entertainment functions, knowledge functions, life functions, smart home, and training plans. Summary/Notes: The Xiao Ai App must be installed on your mobile phone in advance for easy connection and use.

Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Teach you how to use the new advanced features of iOS 17.4 'Stolen Device Protection' Mar 10, 2024 pm 04:34 PM

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

How to use Thunder to download magnet links How to use Thunder to download magnet links Feb 25, 2024 pm 12:51 PM

With the rapid development of network technology, our lives have also been greatly facilitated, one of which is the ability to download and share various resources through the network. In the process of downloading resources, magnet links have become a very common and convenient download method. So, how to use Thunder magnet links? Below, I will give you a detailed introduction. Xunlei is a very popular download tool that supports a variety of download methods, including magnet links. A magnet link can be understood as a download address through which we can obtain relevant information about resources.

See all articles