Home > Web Front-end > JS Tutorial > How Can I Retrieve HTTP Response Content Using XMLHttpRequest and jQuery?

How Can I Retrieve HTTP Response Content Using XMLHttpRequest and jQuery?

Susan Sarandon
Release: 2024-11-29 08:07:13
Original
635 people have browsed it

How Can I Retrieve HTTP Response Content Using XMLHttpRequest and jQuery?

Retrieving HTTP Response Content with XMLHttpRequest

XMLHttpRequest is a powerful tool for asynchronous HTTP requests. By utilizing it, you can effortlessly load remote content into JavaScript variables.

Accessing the Response

To obtain the HTTP response content, access the XMLHttpRequest.responseText property in the XMLHttpRequest.onreadystatechange event handler when XMLHttpRequest.readyState equals XMLHttpRequest.DONE.

Sample Implementation

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if (xhr.readyState == XMLHttpRequest.DONE) {
    alert(xhr.responseText);
  }
}
xhr.open('GET', 'http://foo.com/bar.php', true);
xhr.send(null);
Copy after login

Alternative with jQuery

For enhanced cross-browser compatibility and simplified usage, jQuery offers the $.get() function.

$.get('http://foo.com/bar.php', function(responseText) {
  alert(responseText);
});
Copy after login

Cross-Origin Policy Considerations

When accessing content from a different origin, remember the Same Origin Policy for JavaScript. To bypass this restriction, consider creating a proxy script on your domain.

The above is the detailed content of How Can I Retrieve HTTP Response Content Using XMLHttpRequest and jQuery?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template