浏览器跨域小记

同源政策规定,AJAX请求只能发给同源的网址,否则就报错。

这里写图片描述
* 1. 跨域问题只存在浏览器中,服务器端跨域请求是不存在问题的
* 2. JSONP只支持GET请求
* 3. CORS支持所有类型的HTTP请求,需要在服务器的白名单
* 4. x-requested-with XMLHttpRequest //表明是AJax异步
* 5. 跨域关键,请求头Origin,谷歌插件可测试 RESTful API
* 6. 在别人家网站测试,可以F12打开控制台中测试练习 =。= 污
* 7. 代理服务,扔到服务器上运行,然后拿结果

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <input type="button" value="测试喽" onclick="ajax();" />
  <script type="text/javascript">
    function ajax() {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "http://www.runoob.com/try/ajax/demo_post.php", true);
      xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
      xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
      xhr.send("id=2");
      xhr.onreadystatechange = function doResult() {
        if (xhr.readyState == 4) {//4代表执行完成
          if (xhr.status == 200) {
            document.getElementById("resText").innerHTML = xhr.responseText;
          }
        }
      }
    }
  </script>
</body>
</html>

这里写图片描述

参考链接:http://www.ruanyifeng.com/blog/2016/04/same-origin-policy.html
http://www.ruanyifeng.com/blog/2016/04/cors.html
http://www.runoob.com/ajax/ajax-xmlhttprequest-send.html

猜你喜欢

转载自blog.csdn.net/pintu274111451/article/details/79729315