Home >Web Front-end >JS Tutorial >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(); }
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"); } });
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!