Home Web Front-end JS Tutorial Detailed explanation of the use of AJAX and JavaScript

Detailed explanation of the use of AJAX and JavaScript

Mar 31, 2018 pm 01:39 PM
ajax javascript js

This time I will bring you a detailed explanation of the use of AJAX and JavaScript. What are the precautions when using AJAX and JavaScript? Here are practical cases, let’s take a look.

AJAX is not a JavaScript specification, it is just an abbreviation "invented" by a buddy: Asynchronous JavaScript and XML, which means using JavaScript to perform asynchronous network requests.

If you carefully observe the submission of a Form, you will find that once the user clicks the "Submit" button and the form begins to submit, the browser will refresh the page and then tell you in the new page whether the operation was successful or not. Failed. If unfortunately the network is too slow or for other reasons, you will get a 404 page.

This is how the Web works: one HTTP request corresponds to one page.

If you want the user to stay in the current page and make a new HTTP request at the same time, you must use JavaScript to send the new request. After receiving the data, use JavaScript to update the page. In this way, the user will feel You still stay on the current page, but the data can be continuously updated.

The earliest large-scale use of AJAX was Gmail. After the Gmail page was loaded for the first time, all remaining data relied on AJAX to update.

Writing a complete AJAX code in JavaScript is not complicated, but you need to pay attention: AJAX requests are executed asynchronously, that is, the response must be obtained through the callback function.
Writing AJAX on modern browsers mainly relies on XMLHttpRequestObject:

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

function success(text) {

 var textarea = document.getElementById('test-response-text');

 textarea.value = text;

}

function fail(code) {

 var textarea = document.getElementById('test-response-text');

 textarea.value = 'Error code: ' + code;

}

var request = new XMLHttpRequest(); // 新建XMLHttpRequest对象

request.onreadystatechange = function () { // 状态发生变化时,函数被回调

 if (request.readyState === 4) { // 成功完成

  // 判断响应结果:

  if (request.status === 200) {

   // 成功,通过responseText拿到响应的文本:

   return success(request.responseText);

  else {

   // 失败,根据响应码判断失败原因:

   return fail(request.status);

  }

 else {

  // HTTP请求还在继续...

 }

}

// 发送请求:

request.open('GET''/api/categories');

request.send();

alert('请求已发送,请等待响应...');

Copy after login

For lower versions of IE, you need to change to an ActiveXObject object:

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

function success(text) {

 var textarea = document.getElementById('test-ie-response-text');

 textarea.value = text;

}

function fail(code) {

 var textarea = document.getElementById('test-ie-response-text');

 textarea.value = 'Error code: ' + code;

}

var request = new ActiveXObject('Microsoft.XMLHTTP'); // 新建Microsoft.XMLHTTP对象

request.onreadystatechange = function () { // 状态发生变化时,函数被回调

 if (request.readyState === 4) { // 成功完成

  // 判断响应结果:

  if (request.status === 200) {

   // 成功,通过responseText拿到响应的文本:

   return success(request.responseText);

  else {

   // 失败,根据响应码判断失败原因:

   return fail(request.status);

  }

 else {

  // HTTP请求还在继续...

 }

}

// 发送请求:

request.open('GET''/api/categories');

request.send();

alert('请求已发送,请等待响应...');

Copy after login

If you want to mix standard writing and IE writing, you can write like this:

1

2

3

4

5

6

var request;

if (window.XMLHttpRequest) {

 request = new XMLHttpRequest();

else {

 request = new ActiveXObject('Microsoft.XMLHTTP');

}

Copy after login

By detecting whether the window object There is the XMLHttpRequest attribute to determine whether the browser supports the standard XMLHttpRequest. Note, do not use the browser's navigator.userAgent to detect whether the browser supports a certain JavaScript feature. One is because the string itself can be forged, and the other is to determine JavaScript through the IE version. Features will be very complex.

After creating the XMLHttpRequest object, you must first set the callback function of onreadystatechange. In the callback function, usually we only need to judge whether the request is completed by readyState === 4. If it is completed, then based on status === 200Determine whether it is a successful response.
XMLHttpRequestThe object's open() method has 3 parameters. The first parameter specifies whether it is GET or POST. The two parameters specify the URL address, and the third parameter specifies whether to use asynchronous. The default is true, so there is no need to write it.

Note, never specify the third parameter as false, otherwise the browser will stop responding , until the AJAX request is completed. If this request takes 10 seconds, then within 10 seconds you will find that the browser is in a "suspended death" state.

Finally call the send() method to actually send the request. The GET request does not require parameters, and the POST request requires the body part to be passed in as a string or FormData object.

Security restrictions

The URL in the above code uses a relative path. If you change to 'http://www.sina.com.cn/' and run it again, an error will definitely be reported. In the Chrome console, you can also see error message.

This is caused by the browser’s same-origin policy. By default, when JavaScript sends an AJAX request, the domain name of the URL must be exactly the same as the current page.

完全一致的意思是,域名要相同(www.example.comexample.com不同),协议要相同(http和https不同),端口号要相同(默认是:80端口,它和:8080就不同)。有的浏览器口子松一点,允许端口不同,大多数浏览器都会严格遵守这个限制。

那是不是用JavaScript无法请求外域(就是其他网站)的URL了呢?方法还是有的,大概有这么几种:

一是通过Flash插件发送HTTP请求,这种方式可以绕过浏览器的安全限制,但必须安装Flash,并且跟Flash交互。不过Flash用起来麻烦,而且现在用得也越来越少了。

二是通过在同源域名下架设一个代理服务器来转发,JavaScript负责把请求发送到代理服务器:
'/proxy?url=http://www.sina.com.cn'代理服务器再把结果返回,这样就遵守了浏览器的同源策略。这种方式麻烦之处在于需要服务器端额外做开发。

第三种方式称为JSONP,它有个限制,只能用GET请求,并且要求返回JavaScript。这种方式跨域实际上是利用了浏览器允许跨域引用JavaScript资源:

1

2

3

4

5

6

7

8

9

<html>

<head>

 <script src="http://example.com/abc.js"></script>

 ...

</head>

<body>

...

</body>

</html>

Copy after login

JSONP通常以函数调用的形式返回,例如,返回JavaScript内容如下:
foo('data');这样一来,我们如果在页面中先准备好foo()函数,然后给页面动态加一个

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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

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

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

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

See all articles