Home > Web Front-end > JS Tutorial > How Can I Make AJAX Calls Without jQuery?

How Can I Make AJAX Calls Without jQuery?

DDD
Release: 2024-12-20 17:57:11
Original
798 people have browsed it

How Can I Make AJAX Calls Without jQuery?

Making AJAX Calls Without jQuery

In today's web development landscape, AJAX has become a crucial technique for enhancing user experience. While jQuery simplifies the process of making AJAX calls, it's essential to understand how to perform them using vanilla JavaScript.

One approach to making an AJAX call without jQuery is to utilize the XMLHttpRequest (XHR) object. Here's an example:

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

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
           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();
}
Copy after login

In this script, we create an XMLHttpRequest object and set up an event listener for the readystatechange event. When the request is complete (readystate is 4), we check the status code and perform appropriate actions based on the result.

jQuery provides a more concise way to make AJAX calls, as seen here:

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

This script uses the jQuery $.ajax() method, providing more flexibility and code readability. However, it's essential to note that jQuery depends on the inclusion of the jQuery library, whereas the vanilla JavaScript approach works natively in most modern browsers.

The above is the detailed content of How Can I Make AJAX Calls Without jQuery?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template