异步方式
const xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json');
xhr.addEventListener('load', () => { //需要使用回调拿到数据
console.log(xhr.responseText);
})
xhr.send();
status code
const xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json');
xhr.addEventListener('load', ()=>{ //增加对 status code 的判断
if(xhr.status >= 200 && xhr.status <300 || xhr.status === 304)
console.log(xhr.responseText);
else
alert('请求失败')
})
xhr.send();
readyState
const xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json');
xhr.onreadystatechange = () => {
if(xhr.readyState === 4) { // readyState === 4对应load事件
if(xhr.status >= 200 && xhr.status <300 || xhr.status === 304)
console.log(xhr.responseText);
else
alert('请求失败');
}
}
xhr.send();
post请求带参数
const xhr = new XMLHttpRequest();
xhr.open('POST', '/login', true); //post请求
xhr.send('username=wang&pass=123'); //设置请求参数
xhr.addEventListener('load', ()=>{
if(xhr.status >= 200 && xhr.status <300 || xhr.status === 304) {
const data = xhr.responseText;
console.log(data);
}
else {
alert('请求失败')
}
})
get请求带参数
const xhr = new XMLHttpRequest();
xhr.open('GET', '/login?username=wang&pass=123', true); //get请求,带参数
xhr.send();
xhr.addEventListener('load', ()=>{
if(xhr.status >= 200 && xhr.status <300 || xhr.status === 304) {
const data = xhr.responseText;
console.log(data);
}
else {
alert('请求失败')
}
})
封装ajax
function ajax(opts){
let url = opts.url
const type = opts.type || 'GET'
const dataType = opts.dataType || 'json'
const data = opts.data || {}
const onsuccess = opts.onsuccess || function(){}
const onerror = opts.onerror || function(){}
let dataStr = Object.entries(data).map(v => `${v[0]}=${v[1]}`).join('&')
if(type === 'GET' && dataStr != '')
url += '?' + dataStr
const xhr = new XMLHttpRequest()
xhr.open(type, url, true)
xhr.addEventListener('load', ()=>{
if(xhr.status >= 200 && xhr.status <300 || xhr.status ===304) {
if(dataType === 'json')
onsuccess(JSON.parse(xhr.responseText))
else
onsuccess(xhr.responseText)
}
else
console.log('错误码' + xhr.status)
})
xhr.onerror = onerror
if(type === 'GET')
xhr.send()
else
xhr.send(dataStr)
}
ajax({
url: '/data.json',
dataType: 'text',
data: {
username: 'wang',
pass: '123',
},
type: 'GET',
onsuccess: data => console.log(data),
onerror: () => console.log('fail'),
})
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。