【发布时间】:2013-04-01 18:12:10
【问题描述】:
我发现了这个很棒的脚本,它可以根据用户的经度和纬度找到用户的邮政编码。通过阅读代码我发现必须有一个状态ID才能使信息变得可见。我的问题是,是否可以将信息放入状态 ID 的 cookie 中。所以它会根据这个人放置一个邮政编码,我想制作一个该邮政编码的 cookie,以便在我的网站上进一步使用它。它使用地理位置并将信息插入谷歌并获取邮政编码。因此,如果可能,我想捕获该邮政编码并从中创建一个 cookie。任何帮助将不胜感激。谢谢。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<p> </p>
<center>
<p id="status"></p>
<script>
$(function(){
var GETZIP = {
getLocation: function(){
$('#status').text('Searching...');
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(GETZIP.getZipCode, GETZIP.error, {timeout: 7000});//cache it for 10 minutes
}else{
GETZIP.error('Geo location not supported');
}
},
index: 0,
error: function(msg) {
if(msg.code){
//this is a geolocation error
switch(msg.code){
case 1:
$("#status").text('Permission Denied').fadeOut().fadeIn();
break;
case 2:
$("#status").text('Position Unavailable').fadeOut().fadeIn();
break;
case 3:
GETZIP.index++;
$("#status").text('Timeout... Trying again (' + GETZIP.index + ')').fadeOut().fadeIn();
navigator.geolocation.getCurrentPosition(GETZIP.getZipCode, GETZIP.error, {timeout: 7000});
break;
default:
//nothing
}
}else{
//this is a text error
$('#error').text(msg).addClass('failed');
}
},
getZipCode: function(position){
var position = position.coords.latitude + "," + position.coords.longitude;
$.getJSON('proxy.php',{
path : "http://maps.google.com/maps/api/geocode/json?latlng="+position+"&sensor=false",
type: "application/json"
}, function(json){
//Find the zip code of the first result
if(!(json.status == "OK")){
GETZIP.error('Zip Code not Found');
return;
}
var found = false;
$(json.results[0].address_components).each(function(i, el){
if($.inArray("postal_code", el.types) > -1){
$("#status").text(Your zip code: + el.short_name);
found = true;
return;
}
});
if(!found){
GETZIP.error('Zip Code not Found');
}
});
}
}
GETZIP.getLocation();
});
</script>
【问题讨论】:
-
您的问题只是“如何将邮政编码存储在 cookie 中?”。或者还有更多?
-
没有。它如何捕获邮政编码并将其存储在 cookie 中。邮政编码似乎被定义为“el.short_name”,我找不到将其正确存储为 cookie 的方法。
-
你为什么不能把
el.short_name放到一个cookie中?你尝试了什么?你遇到了什么问题? -
我用“el.shortname”尝试了任何东西。我试图将 id 状态转换为表单值,以便我可以轻松地从表单值中创建一个 cookie。但我没有运气。
-
在
$("#status").text(Your zip code: + el.short_name);这一行之后创建一个带有el.short_name的cookie
标签: javascript cookies location geo