一、问答
(一)、什么是同源策略?
同源策略简单的讲就是不同源(只要协议、域名、端口其中的一个不同就算作不同源)的网站之间下面三大类行为将受到限制:
(1) Cookie、LocalStorage 和 IndexDB 无法读取。
(2) DOM 无法获得。
(3) AJAX 请求不能发送。
(二)、什么是跨域?跨域有几种实现形式?
javascript出于安全考虑,不允许不同源间的网站进行文本或脚本间的资源交互,而采用某些技术使得不同源间的网站也能够进行上述行为的技术就叫做跨域;跨域的实现形式有以下几种:
- 1、降域;
- 2、JSONP;(只支持GET请求,无法判断请求是否失败,没有错误处理但其兼容性强,支持老式浏览器,以及可以向不支持CORS的网站请求数据)
- 3、CORS;(支持IE11及以上浏览器)
- 4、HTML5中的PostMessage方法
- 5、通过hash方法
- 6、通过window.name的方法
跨域的8种方法见:前端解决跨域问题的8种方案(最新最全)
(三)、jsonp 的原理是什么?
原理是利用<script>标签的可跨域性,在网页中新添加一个<script>元素,里面的src是用于向服务器请求数据,服务器将数据放在一个指定名字的回调函数给传回来,由于网页已经定义了该函数,因此参数被传回后会立即执行该函数。
(四)、CORS是什么?
CORS是w3c的一个标准,全称是Cross-origin resource sharing 即跨域资源共享,使用它可以实现浏览器向跨源服务器发出XMLHttpRequest请求,从而克服了ajax只能同源使用的限制;需要指出的是CORS需要浏览器及服务器同时支持。
二、练习
(一)、本地搭建服务器,演示同源策略
1. 本地搭建服务器(如果使用 SAE 可创建不同的代码版本,这样可通过1.xxx.sinapp.com和2.xxx.sinapp.com 访问了)
2. 修改 本地host,通过不同域名访问本地服务器。比如访问http://a.com/index.html, http://b.com/ajax.php,本质是在 index.html 里使用 ajax 接口访问 http://b.com/ajax.php 里的数据。
3. 查看输出报错
以下测试均在XAMPP中进行:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
</head>
<body>
<button id="btn">看我不爽就猛戳此处~ 哈哈</button>
<h1 id="content"></h1>
<script>
function ajax(opts){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function() {
if (xhr.readyState == 4 && xhr.status == 200) {
opts.success(xhr.responseText);
document.getElementById("content").innerText=xhr.responseText;
}
if (xhr.readyState == 4 && xhr.status == 404) {
opts.error();
}
};
var dataStr="";
for (var key in opts.data){
dataStr+=key+"="+opts.data[key]+"&";
}
dataStr=dataStr.substr(0,dataStr.length-1);
if (opts.type.toLowerCase()=="get"){
xhr.open("get",opts.url+"?"+dataStr,true);
xhr.send(null);
}
if (opts.type.toLowerCase()=="post"){
xhr.open("post",opts.url,true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(dataStr);
}
}
document.querySelector('#btn').addEventListener('click', function(){
ajax({
url: 'http://127.0.0.1:8081/renwu24_1.php', //接口地址
type: 'get', // 类型, post 或者 get,
data: {
username: 'xiaoming',
password: 'abcd1234'
},
success: function(ret){
console.log(ret); // {status: 0}
},
error: function(){
console.log('出错了')
}
})
});
</script>
</body>
</html>
将上述代码放在我http://127.0.0.1:8080/renwu24_1.html 路径中(8080端口),而我把请求的ajax的url写成http://127.0.0.1:8081/renwu24_1.php (8081端口)
上述代码运行后,会报错:
因为正常情况下,不同源网站间不允许ajax请求;
(二)、至少使用一种方式解决跨域问题
1、cors跨域资源共享解决跨域问题:
例如对于上面的例子,我们可以在php文件中添加header('Access-Control-Allow-Origin: http://127.0.0.1:8080');
这一行代码即可:
<?php
header('Access-Control-Allow-Origin: http://127.0.0.1:8080');
echo "你的用户名是". $_REQUEST["username"];
echo " ";
echo "你的密码是".$_REQUEST["password"];
?>
这样便可实现ajax的跨域请求;
2、使用jsonp方法解决跨域问题:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>跨域</title>
</head>
<body>
<script>
function addScriptTag(src) {
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.src = src;
document.body.appendChild(script);
}
function foo(data) {
console.log('Your public IP address is: ' + data.ip);
};
window.onload = function () {
addScriptTag('http://127.0.0.1:8081/renwu24_1.php');
}
</script>
</body>
</html>
以上代码我放在:http://127.0.0.1:8080/renwu24_1.html (8080端口)中,然后在http://127.0.0.1:8081/renwu24_1.php (8081端口)中写如下代码:
foo({
"ip": "8.8.8.8"
});
这样代码运行后,会直接在控制台打出:Your public IP address is: 8.8.8.8
**本文版权归本人即简书笔名:该账户已被查封 所有,如需转载请注明出处。谢谢! *