JSONP 是什么
JSON(JSON with Padding)是 JSON 的一种“使用模式”,可用于解决主流浏览器的跨域数据访问的问题。
利用< script>元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP。
< script>元素实现
网页通过添加一个
function addScripTag(src) {
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.src = src;
document.body.appendChild(script);
}
window.onload = function () {
addScripTag("http://127.0.0.1:3000?callback=foo");
};
function foo(data) {
console.log("your public IP address is:" + data.ip);
}
$.getJSON()方法
jQuery 中的$.getJSON()方法允许通过使用 JSON 形式的回调函数来加载其他网域的 JSON 数据。
$.getJSON("http://127.0.0.1:3000?callback=?", function (data) {
console.log(data);
});
注意:$.getJSON()方法的第一个参数表示 url,需要在该参数后面添加“callback=?”。jQuery 将“ ?”自动替换为正确的函数名,以执行回调函数。