Home >Web Front-end >JS Tutorial >How to implement AJAX request?

How to implement AJAX request?

Guanhui
GuanhuiOriginal
2020-06-24 15:31:052778browse

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");}

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);
  }}

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

xhr.open("GET", "xhr_info.txt");

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

xhr.send(null);

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

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!

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