function ajax(method, url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
};
xhr.open(method, url, true);
if (method == 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.send(data);
}
在这个函数中,我们首先创建一个XMLHttpRequest对象,并设置其onreadystatechange
事件处理函数,该函数会在服务器响应数据时被调用。在处理函数中,我们首先检查readyState
和status
属性是否为4和200,这表示服务器已经成功响应了请求并返回了数据。如果满足条件,我们将响应数据作为参数传递给回调函数。
接下来,我们使用open
方法打开一个请求,并指定请求的方法、URL和是否使用异步模式。如果请求方法为POST,则我们还需要使用setRequestHeader
方法设置请求头,以指定请求数据的格式。最后,我们使用send
方法发送请求,并将数据作为参数传递。
你可以在调用ajax函数时,传入相应的参数,例如:
ajax('GET', 'https://example.com/api', null, function(response) {
console.log(response);
});
ajax('POST', 'https://example.com/api', 'name=John&age=30', function(response) {
console.log(response);
});
上述代码分别发送了一个GET请求和一个POST请求,请求的URL为https://example.com/api,回调函数用于处理服务器响应数据。你可以根据需要,修改ajax函数的实现,以支持更多的请求方法和功能。