JSONP跨域 ajax请求

前端之家收集整理的这篇文章主要介绍了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);}

猜你在找的Json相关文章