跨域就是js在不同的域之间进行数据传输或者通信。
协议不同 端口不同 主机名不同 会产生跨域的问题,跨域意味着拿不到数据。
解决方案
1.通过JSONP跨域 也叫src跨域 ,通过给后台传递回调函数,来返回数据。
function addScriptTag(src) {
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.src = src;
document.body.appendChild(script);
}
window.onload = function () {
addScriptTag('http://example.com/ip?callback=foo');
}
function foo(data) {
console.log('response data: ' + JSON.stringify(data));
};
CORS 请求原理
Cross-origin resource sharing 跨域资源共享。 php 允许后台跨域 在里面配置 header('Access-Control-Allow-Origin: * '); *代表允许所有域名都访问我。
var http = new XMLHttpRequest();
http.open("post", "http://127.0.0.1:8080/0616/insert.php");
http.send();
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
console.log(http.response);
}
}