ajax面试知识点

1. 手写一个简易的ajax

const xhr = new XMLHttpRequest()
// get请求
xhr.open('GET', '/data/test.json', true)
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            // console.log(
            //     JSON.parse(xhr.responseText)
            // )
            alert(xhr.responseText)
        } else if (xhr.status === 404) {
            console.log('404 not found')
        }
    }
}
xhr.send(null)

// post请求
xhr.open('POST', '/data/test.json', true) // true为异步请求,false为同步请求
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
        if (xhr.status === 200) {
            // console.log(
            //     JSON.parse(xhr.responseText)
            // )
            alert(xhr.responseText)
        } else if (xhr.status === 404) {
            console.log('404 not found')
        }
    }
}
constpostData= { userName: 'zhangsan', password: '123456' }
xhr.send(JSON.stringify(pastData))

2. xhr.readyState

  • 0: (未初始化)还没投调用send()方法
  • 1:(载入)以调用send()方法,正在发送请求
  • 2:(载入完成)send()方法执行完成,已经接收到全部响应内容
  • 3:(交互)正在解析响应内容
  • 4:(完成)响应内容解析完成,可以在客户端调用

3. 跨域

同源策略:

  • ajax请求时,浏览器要求当前网页和server必须同源
  • 同源:协议、域名、端口三者必须一致

加载图片、CSS、JS 可无视同源策略

  • 可用于统计打点,可使用第三方统计服务

你可能感兴趣的:(ajax面试知识点)