简体   繁体   English

使用接受语言标题来猜测用户的国家/地区(如果可用)

[英]Using accept language header to guess user's country, if available

I want to use Javascript/PHP to determine if a user's browser has a country (locale variant) defined in the accept-language header.我想使用 Javascript/PHP 来确定用户的浏览器是否在接受语言标头中定义了国家/地区(区域设置变体)。

Knowing that the contents of the accept-language header value can vary, and is not always accurate, is there a way to logically determine if a country present in the accept-language header string?知道 accept-language 标头值的内容可能会有所不同,并且并不总是准确的,有没有办法从逻辑上确定某个国家/地区是否存在于 accept-language 标头字符串中? And then extract that via JS?然后通过JS提取它?

For example, if a user's accept language header contains en-US, I would want to set a local variable="US".例如,如果用户的接受语言标头包含 en-US,我想设置一个局部变量 =“US”。

My intial thought was to create a very large array of all accept header language and locale values and check against that, but that did not seem like a very efficient approach.我最初的想法是创建一个包含所有接受头语言和区域设置值的非常大的数组并进行检查,但这似乎不是一种非常有效的方法。

The Accept-Language header has a couple of formats it can take, see the documentation on MDN . Accept-Language标头有几种可以采用的格式, 请参阅 MDN 上的文档 Getting the preferred languages as a structured list (like an array sorted by q-factor) is just a matter of parsing that list in a way that is resilient to all the possible permutations of the header values.将首选语言作为结构化列表(如按 q-factor 排序的数组)只是以一种对标头值的所有可能排列具有弹性的方式解析该列表的问题。

Instead of trying to write this logic yourself, it's simpler to use a library built for this exact purpose, which will be better at handling all kinds of weird edge-cases.与其尝试自己编写此逻辑,不如使用为此确切目的构建的库更简单,这将更好地处理各种奇怪的边缘情况。 For example, willdurand/Negotiation allows you to parse the Accept-Language header and match it to a list of locales supported by your site to find the best language to use.例如, willdurand/Negotiation允许您解析Accept-Language标头并将其与站点支持的区域设置列表相匹配,以找到要使用的最佳语言。

You will have to do this on the server-side (in PHP).您必须在服务器端(在 PHP 中)执行此操作。 Once you know the language, you can pass that to client-side JavaScript in a number of ways.一旦您了解了该语言,您就可以通过多种方式将其传递给客户端 JavaScript。 For example, you can use the JS tag to include a piece of JavaScript in your page template that sets a global variable with the determined language.例如,您可以使用JS 标记在您的页面模板中包含一段 JavaScript,它使用确定的语言设置全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM