使用 javascript(客户端)获取访问者的语言和国家/地区代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17680413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get visitors language & country code with javascript (client-side)
提问by Sergio
Question:Is there a javascript (client-side) code to get visitors country/language code, that is accurate and is cross-"modern"-browser ? I am looking for results like 'en-US'
, 'sv-SE'
, 'nl-NL'
, etc.
问题:是否有一个 javascript(客户端)代码来获取访问者的国家/语言代码,它是准确的并且是跨“现代”浏览器的?我要寻找的结果一样'en-US'
,'sv-SE'
,'nl-NL'
,等。
Related questions to this have been asked before (some SO links: 1,2,3,4, among others) but I didn't find answer and some of the answers are some yearls old and in some cases referring to even more old articles, which makes me think there are new solutions for this.
之前已经问过与此相关的问题(一些 SO 链接:1、2、3、4等),但我没有找到答案,有些答案已经过时了,在某些情况下甚至引用了更旧的文章,这让我觉得有新的解决方案。
I tried :
我试过 :
var language = window.navigator.userLanguage || window.navigator.language;
console.log(language);
and got "sv"
in Chrome and "en-GB"
in Firefox, in the same machine, same place.
并进入"sv"
Chrome 和"en-GB"
Firefox,在同一台机器上,同一个地方。
采纳答案by Tim
navigator.language
isn't reliable as one of your linked questions states.
navigator.language
正如您的链接问题之一所述,不可靠。
The reason this is asked a lot, but you're still searching says something about the problem. That language detection purelyon the client side is not anything close to reliable.
这个问题被问到很多,但你仍在搜索的原因说明了这个问题。纯粹在客户端进行的语言检测是不可靠的。
First of all language preferences should only be used to detect language preferences - i.e. not location. My browser is set to en_US
, because I wanted the English version. But I'm in the UK, so would have to alter this to en_GB
to have my country detected via my browser settings. As the 'customer' that's not my problem. That's fine for language, but no good if all the prices on your site are in $USD.
首先,语言偏好应该只用于检测语言偏好——即不是位置。我的浏览器设置为en_US
,因为我想要英文版。但我在英国,所以必须改变它才能en_GB
通过我的浏览器设置检测到我的国家。作为“客户”,这不是我的问题。这对语言来说很好,但如果您网站上的所有价格都以美元为单位,那就不好了。
To detect languageyou really do need access to a server side script. If you're not a back end dev and want to do as much as possible on the client side (as your question), all you need is a one line PHP script that echos back the Accept-Languageheader. At its simplest it could just be:
要检测语言,您确实需要访问服务器端脚本。如果您不是后端开发人员并且希望在客户端尽可能多地做(如您的问题),您所需要的只是一个单行 PHP 脚本,它与Accept-Language标头相呼应。最简单的它可能只是:
<?php
echo $_SERVER['HTTP_ACCEPT_LANGUAGE'];
// e.g. "en-US,en;q=0.8"
You could get this via Ajax and parse the text response client side, e.g (using jQuery):
您可以通过 Ajax 获取并解析文本响应客户端,例如(使用 jQuery):
$.ajax( { url: 'script.php', success: function(raw){
var prefs = raw.split(',');
// process language codes ....
} } );
If you were able to generate your HTML via a back end, you could avoid using Ajax completely by simply printing the language preferences into your page, e.g.
如果您能够通过后端生成 HTML,则可以通过简单地将语言首选项打印到您的页面中来完全避免使用 Ajax,例如
<script>
var prefs = <?php echo json_encode($_SERVER['HTTP_ACCEPT_LANGUAGE'])?>;
</script>
If you had no access to the server but could get a script onto another server, a simple JSONP service would look like:
如果您无法访问服务器但可以将脚本放到另一台服务器上,那么简单的 JSONP 服务将如下所示:
<?php
$prefs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$jsonp = 'myCallback('.json_encode($prefs).')';
header('Content-Type: application/json; charset=UTF-8', true );
header('Content-Length: '.strlen($jsonp), true );
echo $jsonp;
Using jQuery for your Ajax you'd do something like:
为您的 Ajax 使用 jQuery,您可以执行以下操作:
function myCallback( raw ){
var prefs = raw.split(',');
// process language codes ....
}
$.ajax( {
url: 'http://some.domain/script.php',
dataType: 'jsonp'
} );
Country detectionis another matter. On the client side there is navigator.geolocation, but it will most likely prompt your user for permission, so no good for a seamless user experience.
国家检测是另一回事。在客户端有navigator.geolocation,但它很可能会提示您的用户获得许可,因此对无缝用户体验没有好处。
To do invisibly, you're limited to geo IP detection. By the same token as above, don't use language to imply country either.
要进行隐形,您仅限于地理 IP 检测。同上,也不要使用语言来暗示国家。
To do country detection on the client side, you'll also need a back end service in order to get the client IP address and access a database of IP/location mappings. Maxmind's GeoIP2 JavaScript clientappears to wrap this all up in a client-side bundle for you, so you won't need your own server (although I'm sure it will use a remote jsonp service). There's also freegeoip.net, which is probably less hassle than MaxMind in terms of signing up, and it appears to be open source too.
要在客户端进行国家/地区检测,您还需要后端服务以获取客户端 IP 地址并访问 IP/位置映射数据库。Maxmind 的 GeoIP2 JavaScript 客户端似乎为您将所有这些都包装在客户端包中,因此您不需要自己的服务器(尽管我确定它将使用远程 jsonp 服务)。还有freegeoip.net,它在注册方面可能没有 MaxMind 那么麻烦,而且它似乎也是开源的。
回答by Sean McClory
Using jQuery, this line will display your user's country code.
使用 jQuery,此行将显示您用户的国家/地区代码。
$.getJSON('https://freegeoip.net/json/', function(result) {
alert(result.country_code);
});
回答by Jonathan
Getting the Country Code with ipdata.co
使用ipdata.co获取国家代码
This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signupfor your own Free API Key and get up to 1500 requests daily for development.
这个答案使用了一个非常有限的“测试”API 密钥,仅用于测试几个调用。注册您自己的免费 API 密钥,每天最多可获得 1500 个开发请求。
$.get("https://api.ipdata.co?api-key=test", function (response) {
$("#response").html(response.country_code);
}, "jsonp");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="response"></pre>