0

我正在尝试利用 Google 的 API 作为获取用户位置的一种方式。完成此操作后,我将其传递给外部 PHP 脚本,该脚本将进一步输出一些 JavaScript 代码。但是,我无法调用 PHP 脚本:

<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAKw7Q"></script
<script type="text/javascript">
    if(google.loader.ClientLocation)
    {
        visitor_countrycode = google.loader.ClientLocation.address.country_code;
    }
</script>
<script type='text/javascript' src='http://www.mysite.com/widget.php?mid=12&c=visitor_countrycode'>
</script>

以上是从我的数据库中检索到的内容。然而,该变量visitor_countrycode不会在 HTML 中生成,它仍然包含字符串“ visitor_countrycode”而不是其 Javascript 值。

我就是想不通。

更新

我实际上可以使用 JQuery:

我已经尝试过了,但我没有得到太多的运气。

$("<script type='text/javascript' scr='http://www.mysite.com/widget.php?mid=12&c="+visitor_countrycode+"'").appendTo('body');

有什么问题吗?

4

2 回答 2

3

对,这行:

<script type='text/javascript' src='http://www.mysite.com/widget.php?mid=12&c=visitor_countrycode'>
</script>

...只是检索 URL,“ http://www.mysite.com/widget.php?mid=12&c=visitor_countrycode ”。该变量没有被评估——它被作为一个普通参数传递。

如果要获取动态生成的 URL,则必须创建一个新的 <script> 元素并将其附加到头部。像这样:

var visitor_countrycode = 'foo';

// create the new script element
var script_element = document.createElement('script');

// visitor_countrycode will be evaluated here.
script_element.src = 'http://www.mysite.com/widget.php?mid=12&c=' + visitor_countrycode;

// this gets the <head>, and then appends the newly-created script element.
document.getElementsByTagName('head')[0].appendChild(script_element);

瞧。

于 2009-08-15T16:19:21.367 回答
0

您也可以使用简单的 HTTP 请求来调用该 PHP 脚本,这样您甚至可以根据 PHP 脚本是否正确处理您的请求来获取结果并执行某些操作。

<script type="text/javascript">
var http = false;

if(google.loader.ClientLocation)
{
    visitor_countrycode = google.loader.ClientLocation.address.country_code;

    if(navigator.appName == "Microsoft Internet Explorer") {
        http = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        http = new XMLHttpRequest();
    }

    http.open("GET", 'http://www.mysite.com/widget.php?mid=12&c=' + visitor_countrycode);
    http.send(null);
}
</script>
于 2009-08-15T16:24:37.473 回答