// 1. 创建 XMLHttpRequest 对象 |
|---|
var xhr = new XMLHttpRequest(); |
|---|
// 2. 配置请求:方法(GET/POST)、URL、是否异步 |
|---|
xhr.open('GET', 'https://api.example.com/data', true); |
|---|
// 3. 注册回调函数,监听请求状态 |
|---|
xhr.onreadystatechange = function() { |
|---|
if (xhr.readyState === 4) { // 请求完成 |
|---|
if (xhr.status === 200) { // 请求成功 |
|---|
console.log('返回数据:', xhr.responseText); |
|---|
} else { |
|---|
console.error('请求失败,状态码:', xhr.status); |
|---|
} |
|---|
} |
|---|
}; |
|---|
// 4. 发送请求 |
|---|
xhr.send(); |
|---|
XMLHttpRequest()。xhr.open(),指定请求方式、URL、是否异步。onreadystatechange 或 onload。xhr.send()。xhr.responseText(文本)、xhr.responseXML(XML) 或 JSON 解析。$.ajax({ |
|---|
url: 'https://api.example.com/data', // 请求地址 |
|---|
type: 'GET', // 请求方式 |
|---|
dataType: 'json', // 数据类型 |
|---|
success: function(response) { // 请求成功回调 |
|---|
console.log('返回数据:', response); |
|---|
}, |
|---|
error: function(xhr, status, error) { // 请求失败回调 |
|---|
console.error('请求失败:', status, error); |
|---|
} |
|---|
}); |
|---|
$.get(), $.post())。XMLHttpRequest / jQuery💡 特点:整个过程 不刷新页面,用户体验更流畅。
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(JSON.stringify({name: "阿杰"}));xhr.timeout = 5000; // 5秒超时 xhr.ontimeout = function(){ console.error('请求超时'); }https://www.52runoob.com/archives/6629
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。