Home > Web Front-end > JS Tutorial > body text

How to implement AJAX request?

Guanhui
Release: 2020-06-24 15:31:05
Original
2752 people have browsed it

How to implement AJAX request?

How to implement AJAX request?

1. Create an XMLHttpRequest instance;

var xhr;if(window.XMLHttpRequest) {
  //ie7+,firefox,chrome,safari,opera
  xhr = new XMLHttpRequest();}else {
  //ie5,ie6
  xhr = new ActiveXObject("Microsoft.XMLHTTP");}
Copy after login

2. Listen to the readystatechange event and determine the request status through the readyState attribute;

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

3. Call open() The method specifies the request type and address;

xhr.open("GET", "xhr_info.txt");
Copy after login

4. Just call the send() method to send the request.

xhr.send(null);
Copy after login

Complete code

var xhr;
if(window.XMLHttpRequest) {
  //ie7+,firefox,chrome,safari,opera
  xhr = new XMLHttpRequest();
} else {
  //ie5,ie6
  xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
  if(xhr.readyState==4 && xhr.status==200) {
    console.log(xhr.responseText);
  }
}
xhr.open("GET", "xhr_info.txt", true);
xhr.send(null);
Copy after login

Recommended tutorial: "JS Tutorial"

The above is the detailed content of How to implement AJAX request?. 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