我不认为现在可以通过javascript直接设置recaptcha语言。正如你所说的那样,在脚本加载过程中可以使用参数'hl'。
如果您需要在不重新加载页面的情况下动态更改应用程序的语言,可以通过从头部删除recaptcha脚本链接来完成此操作,而是直接使用javascript调用加载它。当用户通过单击按钮更改语言时,您现在可以通过再次调用加载函数来使用新语言重新加载recaptcha。
在我的情况下,recaptcha元素显示在模态内,用户响应通过ajax发送到服务器,并在服务器端针对Google进行验证。 像这样的伎俩:
/* Clears recaptcha HTML element of all content, clears
* recaptcha element id so that the code would know to create
* the new HTML. Reloads recaptcha code with the new specified
* language using jQuery */
var captchaReload = function(langCode) {
$('#recaptchaDiv').empty();
recaptchaElement = null;
var url = "https://www.google.com/recaptcha/api.js?render=explicit&hl=" + langCode;
$.getScript(url);
};
/* Called by recaptcha when the user solves the puzzle.
* The incoming parameter 'response' is generated by the recaptcha
* and needs to be validated against google separately, which
* is not shown here */
var captchaValidate = function(response){
console.log('Doing captcha response: ' + response);
grecaptcha.reset();
$('#captchaModal').modal('hide');
// TODO: Add server side call for validating the client response
};
/* Variable for keeping track if recaptcha has already been created */
var recaptchaElement = null;
/* Called for initializing the recaptcha element and opening the modal */
var captchaShow = function() {
// Initialize recaptcha if it is not present yet
if(recaptchaElement === null){
recaptchaElement = grecaptcha.render('recaptchaDiv', {
'sitekey' : 'YoUrReCaPtChAsItEkEy',
'theme' : 'light',
'callback' : captchaValidate
});
}
// Open captcha modal
window.setTimeout(function() {
$('#captchaModal').modal('show');
},300);
};
现在,在页面加载或当用户选择一个新的语言,你可以这样做:
captchaReload('fr');
它应该从删除现有的reCAPTCHA对象页面并用正确的语言重新加载一个。之后,你可以使用打开模式:
captchaShow();
您需要重新加载页面或破坏HTML元素和脚本在一个新的,为了做到。注意说明reCaptcha ID或reCaptcha容器必须为空的错误。 – colecmc