gpt4 book ai didi

javascript - 随机谷歌未定义错误

转载 作者:行者123 更新时间:2023-11-29 23:18:30 25 4
gpt4 key购买 nike

我多次重新加载页面时出现以下错误。

Uncaught ReferenceError: google is not defined

虽然这不是我经常遇到的错误。

以下是我的javascript代码:

$('document').ready(function () {
var apiKey = '@System.Configuration.ConfigurationManager.AppSettings["googleAPIKey"]';
var language = $('#Language').text();
var n = language.indexOf('-');
language = language.substring(0, n != -1 ? n : language.length);
var s = document.createElement("script");
s.type = "text/javascript";
s.id = "gogapi"
s.src = "https://maps.googleapis.com/maps/api/js?key=" + apiKey + "&libraries=places&language=" + language + "&callback=initialize";
document.head.appendChild(s);
if ($("#Country").val() != '') {
updateCityLoad($("#Country").val(), "City");
}
});


function updateCityLoad(country, city) {
getCountryCode(country, function (code) {
initialize(code, city)
});
}

function getCountryCode(countryId, callback) {
var countryCode = "";
$.getJSON('@Url.Action("GetCountryCode", "TestController")' + "&countryId=" + countryId, function (result) {
countryCode = result.data;
callback(countryCode);
});
}

function initialize(country, cityID) {
var cityfield = document.getElementById(cityID);
var options = {
types: ['(cities)'],
componentRestrictions: { country: country },
};
var autocomplete = new google.maps.places.Autocomplete(cityfield, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
place = autocomplete.getPlace();
$(cityfield).val(place.address_components[0].long_name);
})
}

我正在做的是在更改国家字段和加载页面时调用函数 upDateCity,如果国家字段不为空,则加载 google api。在 document.ready 上调用函数 updateCityLoad 时,我收到了谷歌错误。

知道如何解决这个问题吗?

最佳答案

我敢打赌,在您的 $(document).ready(){} 中调用 updateCityLoad 之前,您尝试引用的脚本 (googleapi) 没有被及时检索

您可以在它被调用之前设置一个超时,在您的 html 标记的 header 标签中呈现脚本,或者可能尝试在追加之后再次调用 $(document).ready()。像...

$('document').ready(function () {
var apiKey = '@System.Configuration.ConfigurationManager.AppSettings["googleAPIKey"]';
var language = $('#Language').text();
var n = language.indexOf('-');
language = language.substring(0, n != -1 ? n : language.length);
var s = document.createElement("script");
s.type = "text/javascript";
s.id = "gogapi"
s.src = "https://maps.googleapis.com/maps/api/js?key=" + apiKey + "&libraries=places&language=" + language + "&callback=initialize";
document.head.appendChild(s);

$(document).ready(function(){//additional call here to wait for document to load
if ($("#Country").val() != '') {
updateCityLoad($("#Country").val(), "City");
}
});
});

关于javascript - 随机谷歌未定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51726735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com