JSONP跨域 ajax请求

 

原理:

由于浏览器的同源策略不能使用XMLHTTPREQUEST对除本地外的服务器发送请求。

所以使用script标签的src属性发送请求,接收到的JSONP数据以函数名的方式返回。

需要在本地创建服务器返回的函数接收服务器返回的数据。


JS代码:

function jsonpRequest() {
var create_src = document.createElement('srcipt'); #创建script标签
create_src.src = 'http://www.baidu.com';    #给script标签加入src请求地址
document.head.appendChild(create_src);      #把script标签添加到head标签内
document.head.removeChild(create_src);      #把script标签在head标签内删除

}

function f(arg) {
console.log(arg)
}



jquery代码:

$.ajax({
url:'http//xxxxx',
type:'GET' 或 'POST',
dataType:JSONP
})

function xxx(arg){
  console.log(arg);
}

猜你喜欢

转载自www.cnblogs.com/louzi/p/9248191.html