在JavaScript中,可以使用原生的XMLHttpRequest对象或者现代的fetch API来实现AJAX请求。以下是使用这两种方法的示例代码:
使用XMLHttpRequest的AJAX请求示例:
var xhr = new XMLHttpRequest();
xhr.open("GET", "your-endpoint-url", true); // 第三个参数为true表示异步请求
 
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
        } else {
            console.error("Error: " + xhr.status);
        }
    }
};
 
xhr.timeout = 10000; // 设置超时时间为10秒
xhr.ontimeout = function(event) {
    console.error("The request timed out!");
};
 
xhr.send();使用fetch API的AJAX请求示例:
fetch("your-endpoint-url")
    .then(response => {
        if (response.ok) {
            return response.text();
        }
        throw new Error('Network response was not ok.');
    })
    .then(data => console.log(data))
    .catch(error => console.error('There has been a problem with your fetch operation:', error));在fetch API中,默认情况下请求是异步的,并且它使用Promise来处理异步操作,这使得代码更加简洁。同时,fetch API还提供了更丰富的功能,比如可以直接返回JSON格式的数据等。