JSONP的工作原理

同源策略

跨域的集中方法:

1、服务器端发送请求,服务器作为中继代理(此方法不理解)

2、iframe

3、script标签

  通过动过动态生成script标签,并将src指向目标源的方式(img标签同样具有src属性,用img实现不行吗?)

原生实现方式示例:

var url="www.xxx.baidu.com/aa.js",

  scriptTag=document.createElement("script");

scriptTag.src=url;

document.getElementByTagName("head")[0].appendChild(scriptTag);

function showSth(data){

  alert(data.a);

}

////////////aa.js

var aa={"a":"A"};

showSth(aa);

jsonp:

使用script标签实现跨域访问、可在url中指定回调函数、获取json数据并在指定的回调函数中执行

jQuery实现jsonp

//$.getJSON

var url="wwwa.xxx.baidu.com/aa.js?callback=?"

$.getJSON(url,function(data){

  alert(data.a);

});

//$.ajax;

var url="www.xxx.baidu.com/aa.js"

$.ajax({

  url: url,

  dataType: jsonp,

  success:function(data){

    alert(data.a);

  }

});

jQuery 只支持get方式的jsonp实现

jsonp的缺点:

如果返回的数据格式有问题或返回失败了,并不会报错。

原文地址:https://www.cnblogs.com/charling/p/3330922.html