以下是使用 javascript 原生的 xmlhttprequest 对象进行 ajax 请求的示例代码:
function ajaxrequest(method, url, data, callback) {
var xhr = new xmlhttprequest();
xhr.open(method, url, true);
if (method === 'post') {
xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded');
}
xhr.onreadystatechange = function() {
if (xhr.readystate === 4 && xhr.status === 200) {
callback(xhr.responsetext);
}
};
if (method === 'post') {
xhr.send(data);
} else {
xhr.send();
}
}
// 使用示例
ajaxrequest('get', 'https://example.com/data', null, function(response) {
console.log(response);
});
ajaxrequest('post', 'https://example.com/submit', 'key1=value1&key2=value2', function(response) {
console.log(response);
});
在上述代码中:
- ajaxrequest 函数接受请求方法(method)、请求
url(url)、要发送的数据(data)和回调函数(callback)作为参数。 - 通过 open 方法设置请求的方法和 url,并指定是否异步。 根据请求方法设置相应的请求头。
- 通过 onreadystatechange 事件监听请求状态的变化,当请求完成且状态码为 200 时,调用回调函数处理响应数据。
- 最后根据请求方法发送数据。
例如,在上面的使用示例中,分别进行了 get 和 post 请求,并在回调函数中打印响应的文本内容。
发表评论