Home >Web Front-end >JS Tutorial >How Can I Make AJAX Calls Using Plain JavaScript and jQuery?

How Can I Make AJAX Calls Using Plain JavaScript and jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-28 05:37:091020browse

How Can I Make AJAX Calls Using Plain JavaScript and jQuery?

Performing AJAX Calls in JavaScript

While jQuery simplifies AJAX operations, it is possible to make AJAX calls using plain JavaScript. Here's how:

Vanilla JavaScript:

function loadXMLDoc() {
    const xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState === XMLHttpRequest.DONE) {
            if (xmlhttp.status === 200) {
                document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
            } else if (xmlhttp.status === 400) {
                alert('There was an error 400');
            } else {
                alert('Something else other than 200 was returned');
            }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}

jQuery:

$.ajax({
    url: "test.html",
    context: document.body,
    success: function() {
        $(this).addClass("done");
    }
});

By utilizing the vanilla JavaScript method, you can make AJAX calls directly, providing flexibility and allowing for manipulation of the response without relying on jQuery.

The above is the detailed content of How Can I Make AJAX Calls Using Plain JavaScript and jQuery?. 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