Ajax的简单操作

101 阅读1分钟

一、Ajax的核心API-XMLHttpRequest

1、XMLHttpRequest

const xhr = new XMLHttpRequest()
xhr.open('GET', 'http://127.0.0.1:4523/mock/803545/user/{id}', false) // false表示异步
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            console.log(JSON.parse(xhr.responseText));
            alert(xhr.responseText)
        } else {
            console.log('其他情况');
        }
    }
}
xhr.send(null)

const xhr1 = new XMLHttpRequest()
xhr1.open('POST', 'http://127.0.0.1:4523/mock/803545/login/{username}', true) // true表示异步false同步
xhr1.onreadystatechange = function () {
    if (xhr1.readyState === 4) {
        if (xhr1.status === 200) {
            console.log(JSON.parse(xhr1.responseText));
            alert(xhr1.responseText)
        } else {
            console.log('其他情况');
        }
    }
}
const postData = {
    username: 'xiaoming',
    password: '7878787'
}
xhr1.send(JSON.stringify(postData))

2、同源策略

Ajax请求时,浏览器要求当前网页和server必须同源(安全)
同源:协议、域名、端口,三者必须一致
前端:http://a.com:8080/
server:https://b.com/api/xxx
以上两个三者完全不一样

3、加载 图片、css、js 可无视同源策略

<img src=跨域的图片地址/>
<link href=跨域的css地址/>
<script src=跨域的图片地址></script>

<img />可用于统计打点,可使用第三方统计服务
<link /><script> 可使用CDN,CDN一般都是外域
<script> 可使用JSONP

4、跨域

所有的跨域,都必须经过server端允许和配合
未经server端允许就实现跨域,说明浏览器有漏洞,危险信号

5、跨域的常用实现方式

JSONP

访问https://juejin.cn/,服务端一定返回一个html文件吗?NO
服务端可以任意动态凭借数据返回,只要符合html格式要求
同理,<script src="https://juejin.cn/getData.js">就一定是个静态的js文件吗?NO
<script>可以绕过跨域限制
服务器可以任意动态拼接数据返回
所以,<script>就可以获得跨域的数据,只要服务端愿意返回

CORS - 服务器设置http header

6、手写一个简易的Ajax

// 这个太过简洁了
function ajax(url, successFn) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true)
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                successFn(xhr.responseText)
            }
        }
    }
    xhr.send(null);
}

// 这个好点
function ajax(url) {
    const p = new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(JSON.parse(xhr.responseText))
                } else if (xhr.status === 404) {
                    reject(new Error('404 not found'))
                }
            }
        }
        xhr.send(null)
    })
    return p
}

const url = 'http://127.0.0.1:4523/mock/803545/user/{id}'
ajax(url).then(res => console.log(res)).catch(err => console.log(err))

7、几个常用的ajax工具

jQuery
fetch
axios