2012-04-24 52 views
0

我使用的PHP或HTML文件,该代码重定向重定向从JS文件

<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script> 

<script language="JavaScript"> 


var country= geoip_country_code(); 

if(country == "US") 
{ 
<!-- 
window.location = "http://google.com" 

//--> 
} 

</script> 

,但我想用一个js文件里面做同样的功能,但它的扩展名应该是的.js

as http://domain.com/redirect.js那么代码是什么?

回答

1

这包括带回调的脚本包含函数,以便Maxmind客户端代码在加载Maxmind库之前不会运行。

loadScript("http://j.maxmind.com/app/geoip.js", function() { 
    var country = geoip_country_code(); 

    if (country === "US") { 
     window.location = "http://google.com/"; 
    } 
}); 

function loadScript(url, callback) { 
    // adding the script tag to the head as suggested before 
    var head = document.getElementsByTagName('head')[0]; 
    var script = document.createElement('script'); 
    script.type = 'text/javascript'; 
    script.src = url; 

    // then bind the event to the callback function 
    // there are several events for cross browser compatibility 
    script.onreadystatechange = callback; 
    script.onload = callback; 

    // fire the loading 
    head.appendChild(script); 
} 
+0

伟大的工作感谢 – 2012-04-24 23:19:36

+0

让我知道的最好方法是upvote并选择我的正确答案。 :) – dtbarne 2012-04-24 23:28:38