原生JavaScript ajax实现示例
// 原生JavaScript ajax实现示例
function ajax(method, url, data, success) {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
var paramArr = [];
for (var key in data) {
paramArr.push(key + '=' + data[key]);
}
var postData = paramArr.join('&');
if (method.toLowerCase() === 'post') {
xhr.open(method, url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
xhr.send(postData);
} else if (method.toLowerCase() === 'get') {
xhr.open(method, url + '?' + postData, true);
xhr.send();
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success(xhr.responseText);
}
}
};
}
// 使用示例
var sendData = {
name: 'ChatGPT',
age: '2'
};
ajax('post', '/api/user', sendData, function (data) {
console.log('请求成功,返回数据:', data);
});
用户评论