Performing HTTP GET Requests in JavaScript
HTTP GET requests are a common way to fetch data from servers using JavaScript. Dashcode widgets, available on Mac OS X, provide an XMLHttpRequest object specifically designed for this purpose.
Basic HTTP GET Request
To make a synchronous GET request, use the following code:
function httpGetSync(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", theUrl, false); xmlHttp.send(null); return xmlHttp.responseText; }
Asynchronous HTTP GET Request
For asynchronous requests that will not block the execution of other code, consider the following:
function httpGetAsync(theUrl, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) callback(xmlHttp.responseText); } xmlHttp.open("GET", theUrl, true); xmlHttp.send(null); }
Note on Asynchronous Requests
While synchronous requests may be easier to implement, they are discouraged due to potential performance and user experience impacts. It is generally recommended to make asynchronous requests whenever possible.
The above is the detailed content of How to Perform Synchronous and Asynchronous HTTP GET Requests in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!