我曾经有一个fancybox根据他们访问的国家/地区向用户显示消息,如下所示:
<script>
jQuery.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// If the visitor is browsing from United Kingdom.
if (location.country_code === 'GB') {
// Tell him about U.S. store.
jQuery.fancybox.open(jQuery('#messageGB'));
}
}
});
</script>
<div id="messageGB">
<p>You are visiting our U.S. store. </p>
</div>
我在使用fancybox放置cookie时遇到了一些问题,所以现在我使用的是一个jquery pop up,它可以自行运行,但如果我尝试拨打国家/地区的电话,它就无法工作......对于什么有什么想法我做错了?
// If the visitor is browsing from United Kingdom.
if (location.country_code === 'GB') {
// Tell him about U.S. store.
$('#popup_messageGB').popup({
setcookie: true,
cookie_timeout: 0
}
}
});
</script>
<div id="popup_messageGB">
<p>You are visiting our U.S. store. </p>
</div>
答案 0 :(得分:1)
跨域ajax请求需要以Web服务需要支持的特定方式完成。您正在使用的地理位置服务确实支持&#34; jsonp&#34;跨域请求......所以你很幸运。
请注意添加到查询字符串的回调参数。您的代码缺少回调,这可能是它无法正常工作的原因。
jQuery文档解释了如何进行jsonp调用jQuery.getJSON()
你的jQuery代码看起来像这样:
$.getJSON('http://freegeoip.net/json/?callback=?', function(data) {
// your popup here
});
然而,对于像这样简单的事情,人们并不真正需要jQuery。您只需要检索一次访问者的位置。这可以通过将Web服务URL包含在普通脚本标记中来完成。加载后,它将使用返回的数据调用您的函数。
更新:回复评论
@RobRob - 只需复制下面的代码,添加弹出代码,即可完成。
<!doctype html>
<html>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON('http://freegeoip.net/json/?callback=?', function(location) {
// insert your popup code here
alert( location.country_name );
});
});
</script>
</body>
</html>
以下示例演示了执行jsonp调用的两种方法。
运行代码段以显示您的国家/地区
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<button onclick="getLocation()">jQuery.getJSON</button>
<h2 id="country_name"></h2>
JSON:
<xmp id="stdout" style="border:1px gray solid; background-color:aliceblue;"></xmp>
<script type="text/javascript">
// Method 1: plain Javascript jsonp callback
function onGeoLocation( data ) {
document.getElementById('stdout').innerHTML = JSON.stringify(data,null,' ');
document.getElementById('country_name').innerHTML = 'Country: ' + data.country_name;
// add your popup here
};
// Method 2: Using jQuery
function getLocation() {
$.getJSON('http://freegeoip.net/json/?callback=?', function(data) {
alert( 'jQuery.getJSON\n' + JSON.stringify(data, null, ' '));
// your popup here
});
}
</script>
<!-- This script tag required for method 1 -->
<script type="text/javascript" src="http://freegeoip.net/json/?callback=onGeoLocation"></script>
</body>
</html>
&#13;