第十三章-ajax及跨域

时间:2020-07-28 01:06:12   收藏:0   阅读:109

题目

知识点

ajax核心API-XMLHttpRequest

手写原生Ajax请求

// get 请求
// 初始化ajax实例
const xhr = new XMLHttpRequest()
// true 表示异步请求, false 表示同步请求
xhr.open(‘GET‘, ‘/api‘, true)
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      alert(xhr.responseText)
    } else {
      console.log(‘其他情况‘)
    }
  }
}
xhr.send(null)


// post 请求
// 初始化ajax实例
const xhr = new XMLHttpRequest()
// true 表示异步请求
xhr.open(‘POST‘, ‘/api‘, true)
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      alert(xhr.responseText)
    } else {
      console.log(‘其他情况‘)
    }
  }
}
const postData = {
  userName: ‘zhangsan‘,
  password: ‘123456‘
}

xhr.send(JSON.stringify(postData))

xhr.readyState 取值含义

只有在 readyState 的值为 4 的时候才能拿到 responseText 并使用

xhr.status 取值

跨域

什么是同源策略(浏览器中)?

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

跨域

跨域的常见方式 JSONP 和 CORS

dmeo

<script>
  window.jsonpFun = function (data) {
	console.log(data)
  }
</script>
<script src=‘http://localhost:8081/jsonp.js?name=zhangsan&callback=jsonpFun‘></script>

jQuery 实现 ajax跨域

$.ajax({
  url: ‘http://localhost:8081/jsonp.js‘,
  dataType: ‘jsonp‘,
  jsonpCallback: ‘callback‘,
  success: function (data) {
    console.log(data)
  }
})

CORS-服务器设置 http header

CORS跨域是通过后端实现的,如果后端设置了CORS跨域,那么浏览器就可以直接请求

技术分享图片

手写简易ajax请求

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 && xhr.status === 200) {
		resolve(JSON.parse(xhr.responseText))
      } else {
        reject(new Error(‘error‘))
      }
    }
    xhr.send(null)
  })
  return p
}

const url = ‘/data/test.json‘
ajax(url)
.then(res => {console.log(res)})
.catch(err => {console.log(err)})

实际中常用的ajax插件:jquery使用ajax;fetch(兼容性不好);axios(多用于框架中)

原文:https://www.cnblogs.com/aurora-ql/p/13388049.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!