<!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>