Jquery Cookie没有被正确读取

Jquery Cookie not being read correctly

本文关键字:读取 Cookie Jquery      更新时间:2023-09-26

我正在尝试设置一个cookie,然后阅读它并将其放入我的谷歌地理编码脚本,但它似乎不起作用。应该是这样的,所以只有来自美国的自动建议结果,但你可以在例子中看到,它们是来自每个国家的建议。

这是我正在使用的代码:

http://jsfiddle.net/sR4GR/4/

原始代码:

<script type="text/javascript" src="//maps.google.com/maps/api/js?sensor=true&libraries=places"></script>
<script type="text/javascript" src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>
<script type="text/javascript">
    // SET COOKIE FOR TESTING   
$.cookie("country", "us");
    // GEOCODE RESULT
 function geocode(){
    var GeoCoded = { done: false };
    var input = document.getElementById('loc');
    var options = { types: []};
    var country_code = $.cookie('country');
    if (country_code) { options.componentRestrictions= { 'country': country_code }; }
    var autocomplete = new google.maps.places.Autocomplete(input, options);
    $('#searchform').on('submit',function(e){
       if(GeoCoded.done)
            return true;
        e.preventDefault();
        var geocoder = new google.maps.Geocoder();
        var address = document.getElementById('loc').value;
        $('#searchform input[type="submit"]').attr('disabled',true);
        geocoder.geocode({
            'address': address
        },
        function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                $('#lat').val(results[0].geometry.location.lat());
                $('#lng').val(results[0].geometry.location.lng());
                GeoCoded.done = true;
                $('#searchform').submit();
            } else {
                $('#searchform input[type="submit"]').attr('disabled',false);
                alert("Damn! We couldn't find this location")
            }
        });
    });
};      
</script>
<body onload="geocode()">
<form name="searchform">
        <input class="kw" id="keyword" placeholder="Keyword"></input>
        <input id="loc" placeholder="Location" type="text"></input>
        <input type="submit" value="Search" id="search">
        <input class="hidden" id="lat" disabled="true" placeholder="lat"></input>
        <input class="hidden" id="lng" disabled="true" placeholder="lng"></input>
</form>

上述代码已正确编写并执行。cookie是在Chrome和Firefox浏览器中设置的。在Safari中,默认的cookie设置是"From visited",这是一个相对严格的设置。为了允许设置这些cookie,用户必须更改Safari设置以允许cookie "Always"。"

虽然似乎没有一个优雅的解决方法,一个可能的解决方案是检查cookie是否返回undefined,如果是,提醒用户"请进入设置并打开cookie,这样我的网站可以在您的安全意识设备上有效运行。"Mmkay吗?谢谢。"

这个线程包含更多关于Safari和cookies的信息