Home >Web Front-end >JS Tutorial >How Can I Retrieve HTTP Response Content Using XMLHttpRequest and jQuery?
XMLHttpRequest is a powerful tool for asynchronous HTTP requests. By utilizing it, you can effortlessly load remote content into JavaScript variables.
To obtain the HTTP response content, access the XMLHttpRequest.responseText property in the XMLHttpRequest.onreadystatechange event handler when XMLHttpRequest.readyState equals XMLHttpRequest.DONE.
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);
For enhanced cross-browser compatibility and simplified usage, jQuery offers the $.get() function.
$.get('http://foo.com/bar.php', function(responseText) { alert(responseText); });
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!