Home >Web Front-end >JS Tutorial >How Can I Make AJAX Calls Using Plain JavaScript?
AJAX Calls in Plain JavaScript
Making AJAX calls without jQuery offers greater flexibility and control over network interactions. Here's how to do it:
Creating the Request Object
First, create a new XMLHttpRequest object, which is the core of AJAX calls in plain JavaScript:
var xmlhttp = new XMLHttpRequest();
Handling the Response
Define an onreadystatechange function to monitor the status of the request:
xmlhttp.onreadystatechange = function() { // Check if the request is complete if (xmlhttp.readyState == XMLHttpRequest.DONE) { // Check if the request was successful if (xmlhttp.status == 200) { // Process the response text document.getElementById("myDiv").innerHTML = xmlhttp.responseText; } else { // Handle error conditions by status code alert('There was an error ' + xmlhttp.status); } } };
Sending the Request
Specify the HTTP method, URL, and whether the request is asynchronous or synchronous:
xmlhttp.open("GET", "ajax_info.txt", true); // Asynchronous request is recommended for performance xmlhttp.send();
The above is the detailed content of How Can I Make AJAX Calls Using Plain JavaScript?. For more information, please follow other related articles on the PHP Chinese website!