function ajax(url){
const p = new Promise(resolve,reject)=>{
const xhr=XMLHttpRequest();
xhr.open(‘GET‘, url, true);
xhr.onreadystatechange=function(){
ir(xhr.readystate === 4){
if(xhr.status === 200){
resolve(JSON.parse(xhr.responseText))
}else if(xhr.statue === 404){
reject(new Error(‘404 not found‘))
}
}
}
xhr.send(null)
}
return p;
}
ajax(‘/data/test.json‘)
.then(res=>console.log(res))
.catch(err=>{console.log(err)})
<script />
可实现JSONP<img src=xxImg /> // 服务器可以做防盗链,判断是否是白名单内的域名请求,不是的话返回报错即可
<link href=xx.css /> // 如:在线cdn等
<script src=xx.js /> // 如:在线cdn等
<body>
<script>
window.callback = function(data){
console.log(data)
}
</script>
<script src="http://xx?8990/xx?username=xx&callback=callback"
</body>
// get 请求
const xhr = new XMLHttpRequest()
xhr.open("GET", "/api",true) // 第三个参数true为异步,false为同步
xhr.onreadystatechange = function(){
// 这里的函数异步执行,类似img.onload
if(xhr.readyState === 4 ){
if(xhr.status === 200){
alert(xhr.responseText)
}
}else{
console.log(‘其他情况‘)
}
}
xhr.send(null) // get请求不需要发送数据,xhr发送数据只能发送字符串;通过JSON.stringify(data)转一下就可以了
原文:https://www.cnblogs.com/keepLeung/p/14460631.html