前端之家收集整理的这篇文章主要介绍了
jsonp(跨域)-------可以运行的小实例!,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div id="divCustomers"></div>
<div id="divCustomers2"></div>
<script type="text/javascript">
//通过jquery的get方法实现跨域
$.get('https://ipinfo.io',function() {},"jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "";
countryCode = countryCode.toLowerCase();
$('#divCustomers').text(countryCode);
localStorage.setItem('countryCode',countryCode);
});
//通过jquery的ajax方法实现跨域
$.ajax({
type: "get",dataType:'jsonp',url:'https://ipinfo.io',success:function(resp){
var countryCode = (resp && resp.country) ? resp.country : "";
countryCode = countryCode.toLowerCase();
$('#divCustomers2').text(countryCode);
localStorage.setItem('countryCode',countryCode);
},});
//通过原生javascript的封装的方法实现跨域
function jsonp(setting)
{
setting.data = setting.data || {};
setting.key = setting.key||'callback';
setting.callback = setting.callback||function(){};
setting.data[setting.key] = '__onGetData__';
window.__onGetData__ = function(data) {
setting.callback (data);
}
var script = document.createElement('script');
var query = [];
for(var key in setting.data)
{
query.push(key + '=' + encodeURIComponent(setting.data[key]));
}
script.src = setting.url + '?' + query.join('&');
document.head.appendChild(script);
document.head.removeChild(script);
}
jsonp({
url: 'http://photo.sina.cn/aj/index',key: 'jsoncallback',data: { page: 1,cate: 'recommend' },callback: function(ret) {
console.log(ret)
}
});
</script>
</body>
</html>