I need to do an HTTP GET request in JavaScript. What's the best way to do that?
I need to do this in a Mac OS X dashcode widget.
I need to do an HTTP GET request in JavaScript. What's the best way to do that?
I need to do this in a Mac OS X dashcode widget.
One solution supporting older browsers:
Maybe somewhat overkill but you definitely go safe with this code.
Usage:
The new
window.fetch
API is a cleaner replacement forXMLHttpRequest
that makes use of ES6 promises. There's a nice explanation here, but it boils down to (from the article):Browser support is now good in the latest releases (works in Chrome, Firefox, Edge (v14), Safari (v10.1), Opera, Safari iOS (v10.3), Android browser, and Chrome for Android), however IE will likely not get official support. GitHub has a polyfill available which is recommended to support older browsers still largely in use (esp versions of Safari pre March 2017 and mobile browsers from the same period).
I guess whether this is more convenient than jQuery or XMLHttpRequest or not depends on the nature of the project.
Here's a link to the spec https://fetch.spec.whatwg.org/
Edit:
Using ES7 async/await, this becomes simply (based on this Gist):
IE will cache URLs in order to make loading faster, but if you're, say, polling a server at intervals trying to get new information, IE will cache that URL and will likely return the same data set you've always had.
Regardless of how you end up doing your GET request - vanilla JavaScript, Prototype, jQuery, etc - make sure that you put a mechanism in place to combat caching. In order to combat that, append a unique token to the end of the URL you're going to be hitting. This can be done by:
This will append a unique timestamp to the end of the URL and will prevent any caching from happening.
Prototype makes it dead simple
In jQuery:
Here is code to do it directly with JavaScript. But, as previously mentioned, you'd be much better off with a JavaScript library. My favorite is jQuery.
In the case below, an ASPX page (that's servicing as a poor man's REST service) is being called to return a JavaScript JSON object.