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
Susan SarandonOriginal
2024-11-29 08:07:13610browse

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

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

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