新手调试Pull cookie值并将其用作变量-当前不起作用



我是这方面的新手,但我曾尝试将一些代码组合在一起,但我发现了一些错误,而且似乎不起作用。我想要一些输入来帮助调试它。

我保存了一个名为"country"的cookie,其值为"AZ"。我想使用javascript提取这个cookie并将其存储为变量,然后在我的谷歌地图页面中使用它。这是我的代码:

// Setup variable with blank value
var country_code ='';
// Use read_cookie function to pull "country" value from cookie
if (country_code) var country_code = read_cookie('country');
// Make sure its value is lower case (required)
country_code = country_code.toLowerCase();

然后再往下一点:

var input = document.getElementById('loc');
var options = { types: [], ComponentRestrictions({ 'country': country_code });};
var autocomplete = new google.maps.places.Autocomplete(input, options); 

第一个错误是我在"componentrestriction"行上有太多的括号。应该如何做到这一点?看起来我正确地关闭了它们,我用({})封装了组件限制;和带有{}的var选项;

编辑:这是我在stackoverflow上找到的读取cookie函数代码:

// Reading Cookie V0.1
function read_cookie(key){
var result;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? (result[1]) : null;
}

语句中有一个分号,ComponentRestrictions后面有很多括号。

这样写:

var options = { 
types: [], 
ComponentRestrictions: { 
'country': country_code 
}
};

对于组件限制:

var input = document.getElementById('loc');
var options = { types: [], componentRestrictions: { 'country': country_code } };
var autocomplete = new google.maps.places.Autocomplete(input, options);

最新更新