跨域

2019-03-15  本文已影响0人  benbensheng

https://www.cnblogs.com/yongshaoye/p/7423881.html

1.跨域资源共享(CORS)

<div id="id"></div>
<input type="submit" id="btn">
<script>
var main = document.getElementById("main");
var btn = document.getElementById("btn");
var ajax = new XMLHttpRequest();
btn.onclick = function(){
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200){
main.innerHTML=ajax.responseText;
}
}
ajax.open("POST","http://www.baidu.com",true);
ajax.setRequestHeader('Access-Control-Allow-Origin','*');
ajax.setRequestHeader('Access-Control-Allow-Methods','GET,POST');
//'Access-Control-Allow-Methods:GET,POST'
//响应头设置
//'Access-Control-Allow-Headers:x-requested-with,content-type
ajax.send();
}

2.通过jsonp跨域

<input type="text">
<script>
function GetData(data)
{
("#jsonp").remove(); console.log(data.s); } function getList(wd){ var script = document.createElement('script'); script.src='https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?cb=GetData&wd='+wd; script.id='jsonp'; document.body.appendChild(script); }('input').keyup(function(){
var wd=$(this).val();
getList(wd);
});

使用jq的.getJSON(注意`cb=?`) <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>('input').keyup(function(){
var wd=(this).val();.getJSON('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?cb=?&wd='+wd,function(data){
console.log(data.s);
});
});

3.通过修改document.domain来跨子域

4.使用window.name来进行跨域

5.使用HTML5的window.postMessage方法跨域

上一篇 下一篇

猜你喜欢

热点阅读