I'd like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.
Say, if I wanted to load and alert() the HTML of http://foo.com/bar.php, how would I do that?
I'd like to know how to use XMLHttpRequest to load the content of a remote URL and have the HTML of the accessed site stored in a JS variable.
Say, if I wanted to load and alert() the HTML of http://foo.com/bar.php, how would I do that?
The simple way to use
XMLHttpRequest
withpure JavaScript
. You can setcustom header
but it's optional used based on requirement.1. Using POST Method:
You can send params using POST method.
2. Using GET Method:
Please run below example and will get an JSON response.
I'd suggest looking into
fetch
. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.More Info:
Mozilla Documentation
Can I Use (88% Mar 2018)
Matt Walsh Tutorial
You can get it by
XMLHttpRequest.responseText
inXMLHttpRequest.onreadystatechange
whenXMLHttpRequest.readyState
equals toXMLHttpRequest.DONE
.Here's an example (not compatible with IE6/7).
For better crossbrowser compatibility, not only with IE6/7, but also to cover some browser-specific memory leaks or bugs, and also for less verbosity with firing ajaxical requests, you could use jQuery.
Note that you've to take the Same origin policy for JavaScript into account when not running at localhost. You may want to consider to create a proxy script at your domain.
In
XMLHttpRequest
, usingXMLHttpRequest.responseText
may raise the exception like belowBest way to access the response from XHR as follows