Javascript 需要从另一个外部.JS文件中引用外部脚本
我有一个电子商务网站,我正在创建一个脚本,该脚本将确定我的用户所在的国家,如果它是我们发货到的四个国家之一,那么我们将返回一份声明,说明我们发货到该国家。我可以通过一个ip位置服务脚本(“callback=GetUserInfo”)和一个html文档中的脚本来实现这一点,但是现在我已经尝试将脚本移动到sn external.js文档中,我不知道如何让我的脚本启动ip位置服务脚本 原始HTML文档(工作)Javascript 需要从另一个外部.JS文件中引用外部脚本,javascript,Javascript,我有一个电子商务网站,我正在创建一个脚本,该脚本将确定我的用户所在的国家,如果它是我们发货到的四个国家之一,那么我们将返回一份声明,说明我们发货到该国家。我可以通过一个ip位置服务脚本(“callback=GetUserInfo”)和一个html文档中的脚本来实现这一点,但是现在我已经尝试将脚本移动到sn external.js文档中,我不知道如何让我的脚本启动ip位置服务脚本 原始HTML文档(工作) 查看位置脚本的URL: http://smart-ip.net/geoip-json?cal
查看位置脚本的URL:
http://smart-ip.net/geoip-json?callback=GetUserInfo
我看到callback=GetUserInfo
。这意味着脚本需要在调用此函数之前存在此函数。由于您现在已将此函数移动到脚本之后,因此无法调用它。您将需要两个单独的外部脚本。一个在前调用以设置适当的函数,另一个在后调用以使用结果
作为替代,您可以考虑使用此服务检查是否可以以另一种方式调用它。可能是通过jquery的
ajax
调用jsonp
您的脚本出了问题。这是你需要的
Html:
但是在这种情况下,在检查
if
语句中的值之前,不会设置strcountry
。请从GetUserInfo调用BindUserInfo,而不是在文档准备就绪时调用。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get User Ountry </title>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=GetUserInfo"></script>
</head>
<body>
<a id="weship"/>
<script type="text/javascript" src="countrylocate.js"></script>
</body>
</html>
var strcountry
function GetUserInfo(data) {
strip = data.host;
strcountry = data.countryName;
}
$(function ()
{
BindUserInfo();
})
function BindUserInfo()
{
document.getElementById('lblCountry').innerHTML = strcountry;
}
if (strcountry == "United States")
{
document.getElementById('weship').innerHTML = 'We ship to The United States';
}
else if (strcountry == "Singapore")
{
document.getElementById('weship').innerHTML = 'We ship to Singapore';
}
else if (strcountry == "Malaysia")
{
document.getElementById('weship').innerHTML = 'We ship to Malaysia';
}
else if (strcountry == "Hong Kong")
{
document.getElementById('weship').innerHTML = 'We ship to Hong Kong';
}
http://smart-ip.net/geoip-json?callback=GetUserInfo
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get User Ountry </title>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
</head>
<body>
<label id="lblCountry"></label>
<a id="weship"/>
<script type="text/javascript" src="scripts/countrylocate.js"></script>
<script type="text/javascript" src="http://smart-ip.net/geoip-json?callback=GetUserInfo"></script>
</body>
</html>
function GetUserInfo(data) {
strip = data.host;
strcountry = data.countryName;
document.getElementById('lblCountry').innerHTML = strcountry;
if (strcountry == "United States") {
document.getElementById('weship').innerHTML = 'We ship to The United States';
}
else if (strcountry == "Singapore") {
document.getElementById('weship').innerHTML = 'We ship to Singapore';
}
else if (strcountry == "Malaysia") {
document.getElementById('weship').innerHTML = 'We ship to Malaysia';
}
else if (strcountry == "Hong Kong") {
document.getElementById('weship').innerHTML = 'We ship to Hong Kong';
}
}