以下是一个简单的原生 Ajax 示例,同时满足 GET 和 POST 方法传参的需求:
javascriptCopy code// GET 请求
function get(url, successCallback, errorCallback) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
successCallback(xhr.responseText);
} else {
errorCallback(xhr.statusText);
}
}
};
xhr.send();
}
// POST 请求
function post(url, data, successCallback, errorCallback) {
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
successCallback(xhr.responseText);
} else {
errorCallback(xhr.statusText);
}
}
};
xhr.send(JSON.stringify(data));
}
以上代码定义了两个函数,get
函数用于发送 GET 请求,post
函数用于发送 POST 请求。这两个函数接受参数包括 URL、请求数据、成功回调函数和错误回调函数,可以根据需要进行配置。
在 GET 请求中,使用 xhr.open
方法设置请求的 URL 和请求方法为 GET,通过 xhr.onreadystatechange
事件监听器处理请求完成时的服务器响应。
在 POST 请求中,使用 xhr.open
方法设置请求的 URL 和请求方法为 POST,同时设置 Content-Type
请求头为 application/json;charset=UTF-8
,表示请求数据的格式为 JSON。通过 xhr.onreadystatechange
事件监听器处理请求完成时的服务器响应,并使用 JSON.stringify
方法将请求数据转换为 JSON 字符串后发送。