2016-03-14 855 views
2

我無法弄清楚如何從訪問者的國家代碼獲取到我的網頁。我見過很多其他的例子,但沒有使用純JavaScript。這裏是我當前的代碼:使用javascript獲取國家或地區代碼

<!DOCTYPE html> 
<html lang="en-US"> 
<head> 
</head> 
<body> 
    <script type="text/javascript"> 
     var userip; 
    </script> 
    <script type="text/javascript" src="https://l2.io/ip.js?var=userip">  </script> 

    <script type="text/javascript"> 
     document.write("IP: ", userip); 

     $.get("http://ipinfo.io/"+userip.text(), function (response) { 
      reg.text("country code here" + response.country); 
     }, "jsonp"); 
    </script> 
</body> 
</html> 

我使用jQuery的$.get方法得到JSONP請求用戶的IP addrress到ipinfo.io

不幸的是l2.io.js此時不會返回任何其他的ip。

如果任何人可以提供幫助或有任何示例,請鏈接所有需要的相關JavaScript庫。謝謝。

回答

5

根據網站上的文檔,你應該能夠通過ipinfo檢索國家代碼。嘗試使用$ .getJSON而不是$ .get

var country_code = null; 
$.getJSON('http://ipinfo.io/' + userip, function(data){ 
    country_code = data.country; 
    alert(country_code); 
}); 
+0

我不能理解JavaScript的。我在我目前的$ .get下正好加了。我是否需要包含json .js?我是否需要添加任何代碼中斷或者這個?也許這是工作,那麼我怎麼能把data.country變成一個JavaScript內的變量?並將document.write(variable);實際上工作?我很遺憾和困惑。 – 702cs

+0

刪除當前的$ .get並用上面的代碼替換它,如果它不起作用,控制檯是否會拋出任何錯誤? – Xposedbones

+0

我真的從.html文件和記事本中運行所有這些,所以我不確定是否可以讀取控制檯或看到它。抱歉!我也用你的代替了我當前的$ .get,並試圖做一個document.write(data.country)和document.write(data.country.text())。 – 702cs

0

我已經使用下面的代碼使用jQuery和它的工作對我很好。我得到了country_code,country_name等。

jQuery(document).ready(function($) { 
    jQuery.getScript('http://www.geoplugin.net/javascript.gp', function() 
    { 
     var country = geoplugin_countryName(); 
     alert(country); 
     var code = geoplugin_countryCode(); 
     alert(code); 
     console.log("Your location is: " + country + ", " + zone + ", " + district); 
    }); 
}); 

注意:千萬記得要導入下面的插件腳本:

<script src="http://www.geoplugin.net/javascript.gp" type="text/javascript"></script>

相關問題