2012-04-24 48 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