Home >Web Front-end >JS Tutorial >How to Make HTTP GET Requests in JavaScript: Synchronous vs. Asynchronous?

How to Make HTTP GET Requests in JavaScript: Synchronous vs. Asynchronous?

Linda Hamilton
Linda HamiltonOriginal
2024-12-25 02:23:131000browse

How to Make HTTP GET Requests in JavaScript: Synchronous vs. Asynchronous?

HTTP GET Requests in JavaScript

When tasked with making HTTP GET requests in JavaScript, particularly within a Mac OS X Dashcode widget, it is crucial to leverage the XMLHttpRequest object provided by browsers. Here's a synchronous request example:

function httpGet(theUrl) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open("GET", theUrl, false); // false for synchronous request
    xmlHttp.send(null);
    return xmlHttp.responseText;
}

However, synchronous requests are discouraged due to their potential to impact user experience. Instead, it is recommended to make asynchronous requests and handle the response within an event handler:

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); // true for asynchronous
    xmlHttp.send(null);
}

This approach ensures a more user-friendly experience by avoiding the freezing of main thread operations during data retrieval.

The above is the detailed content of How to Make HTTP GET Requests in JavaScript: Synchronous vs. Asynchronous?. 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