如何从JavaScript发起Ajax调用
Ajax代表异步JavaScript和XML。它用于与服务器进行异步通信。Ajax用于从服务器读取数据并更新页面,或向服务器发送数据而不影响当前客户端页面。Ajax是一个编程概念。
以下是在JavaScript中进行Ajax调用的一些方法:
- 使用XMLHttpRequest对象
 - 使用jQuery
 - 使用fetch() API
 
我们将通过示例探讨上述所有方法及其基本实现。
方法1:使用XMLHttpRequest对象
在这种方法中,我们将使用XMLHttpRequest对象发起Ajax调用。XMLHttpRequest()方法创建一个XMLHttpRequest对象,该对象用于与服务器发起请求。
语法:
let xhttp = new XMLHttpRequest();  
上述语法用于创建XMLHttpRequest对象。该对象有许多不同的方法,用于与服务器进行交互,发送、接收或中断来自服务器的响应。在响应中,我们从服务器获取一个字符串并打印出来。
示例: 在这个示例中,我们将使用XMLHttpRequest对象进行Ajax调用。
Javascript
function run() {
 
    // Creating Our XMLHttpRequest object 
    let xhr = new XMLHttpRequest();
 
    // Making our connection  
    let url = 'https://jsonplaceholder.typicode.com/todos/1';
    xhr.open("GET", url, true);
 
    // function execute after request is successful 
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    }
    // Sending our request 
    xhr.send();
}
run();
输出:
"{  
  "userId": 1,  
  "id": 1,  
  "title": "delectus aut autem",  
  "completed": false  
}"  
方法2:使用jQuery
在这个方法中,我们将使用jQuery来进行Ajax调用。jQuery的 ajax() 方法用于进行ajax调用。它用作替代不起作用的所有方法来进行ajax调用。
语法:
$.ajax({arg1: value, arg2: value, ... });  
参数: 它接受一个配置文件,该文件配置了当我们获得响应或发生错误时要调用的URL、类型和函数等。
示例: 在这个示例中,我们将使用jQuery进行ajax调用。
HTML
<!DOCTYPE HTML>
<html>
 
<head>
    <script src=
"https://code.jquery.com/jquery-3.6.0.min.js">
    </script>
</head>
 
<body>
 
    <script>
 
        function ajaxCall() {
            .ajax({
 
                // Our sample url to make request 
                url:
                    'https://jsonplaceholder.typicode.com/todos/1',
 
                // Type of Request
                type: "GET",
 
                // Function to call when to
                // request is ok 
                success: function (data) {
                    let x = JSON.stringify(data);
                    console.log(x);
                },
 
                // Error handling 
                error: function (error) {
                    console.log(`Error{error}`);
                }
            });
        }
        ajaxCall();
    </script>
</body>
 
</html>
输出:
{  
  "userId": 1,  
  "id": 1,  
  "title": "delectus aut autem",  
  "completed": false  
}  
方法3:使用fetch() API
在这种方法中,我们将使用 fetch() API来与服务器进行XMLHttpRequest。由于它的灵活结构,使用起来很容易。该API向服务器发出请求,并将结果作为一个 promise 解析为字符串。
语法:
fetch(url, {config}).then().catch();  
参数: 需要URL和请求的配置作为参数。
我们会配置所需的数据并向服务器发起请求。由于它是一个已解决的promise,我们使用 then() 函数和 catch() 函数来创建结果的输出。在响应中,我们获取并打印字符串。
示例: 在这个示例中,我们将使用 fetch() API与服务器进行XMLHttpRequest。
Javascript
// Url for the request 
let url = 'https://jsonplaceholder.typicode.com/todos/1';
 
// Making our request 
fetch(url, { method: 'GET' })
    .then(Result => Result.json())
    .then(string => {
 
        // Printing our response 
        console.log(string);
 
        // Printing our field of our response
        console.log(`Title of our response :  ${string.title}`);
    })
    .catch(errorMsg => { console.log(errorMsg); });
输出:
{ userId:1 ,id:1 ,title : "delectus aut autem" ,completed : false  
__proto__:Object }  
Title of our response :  delectus aut autem  
极客教程