解决跨域的方法

前端解决跨域的方法都是基于<script>标签可以跨域请求

平时的ajax请求所经历的过程

const xhr = new XMLHttpRequest()

xhr.onreadystatechange = function () {
  switch (xhr.readyState) {
    case 0:
      // UNSENT (未打开)
      debugger
      break
    case 1:
      // OPENED  (未发送)
      debugger
      break
    case 2:
      // HEADERS_RECEIVED (已获取响应头)
      debugger
      break
    case 3:
      // LOADING (正在下载响应体)
      debugger
      break
    case 4:
      // DONE (请求完成)
      if (xhr.status === 200) {
        console.log(xhr.responseType)
        console.log(xhr.responseText)
        console.log(xhr.response)
      }
      break
  }
}

xhr.open('GET', 'http://y.stuq.com:7001/json', true)
xhr.send(null)

  方法一:

/**
 * 方法1
 */
window.xxx = function (value) {
  console.log(value)
}

var script = document.createElement('script')
script.src = 'http://x.stuq.com:7001/json?callback=xxx'
document.body.appendChild(script)

/**
 * 方法2利用require.js
 */
// require(['http://x.stuq.com:7001/json?callback=define'], function (value) {
//   console.log(value)
// })

  方法二:

var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(JSON.parse(xhr.responseText).msg)
  }
}
// xhr.withCredentials = true
xhr.open('GET', 'http://x.stuq.com:7001/cros')
xhr.send(null)

  方法三(利用iframe)

var iframe = document.createElement('iframe')
iframe.src = 'http://x.stuq.com:7001/public/hash.html'
document.body.appendChild(iframe)

window.onhashchange = function () {
 
  console.log(location.hash)
}

  方法四(利用iframe)

var iframe = document.createElement('iframe')
iframe.src = 'http://x.stuq.com:7001/public/name.html'
document.body.appendChild(iframe)

var times = 0
iframe.onload = function () {
    if (++times === 2) {
        console.log(JSON.parse(iframe.contentWindow.name))
    }
}

  方法五

var iframe = document.createElement('iframe')
iframe.src = 'http://x.stuq.com:7001/public/post.html'
document.body.appendChild(iframe)

window.addEventListener('message', function(e) {
  console.log(JSON.parse(e.data))
}, false);

  

posted @ 2018-03-11 17:50  MC罗  阅读(148)  评论(0编辑  收藏  举报