问题
I want to translate my website using Google Translate. I used the code below.
<div id="google_translate_element"></div><script>
function googleTranslateElementInit() {
new google.translate.TranslateElement({
pageLanguage: 'en'
}, 'google_translate_element');
}
</script><script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
It is working fine with text of the website, but does not translate the text box, text area's text. Is there a solution?
回答1:
You could iterate through the elements in your page and make individual ajax calls to Google Translate API to translate them one by one and them replace the textbox/textarea values.
Using jQuery, you can iterate through your textbox, textareas and everything else you want to. The code should be something like:
$('input:text').each(function(index) {
var elementId = $(this).attr("id");
//Call the Google API
$.ajax({
type : "GET",
url : "https://ajax.googleapis.com/ajax/services/language/translate",
dataType : 'jsonp',
cache: false,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data : "v=1.0&q="+$("#"+elementId).val()+"&langpair=en|es",
success : function(iData){
//update the value
$("#"+elementId).val(iData["responseData"]["translatedText"]);
},
error:function (xhr, ajaxOptions, thrownError){ }
});
});
As you can see, the parameter &langpair=en|es
asks to translate from English to Spanish.
Just remember that one call will be made for each <input type="text".../>
, so you might want to add some kind of validation to filter useless calls! You might also want to validate Google's answer.
Here is a link in order to understand the kind of response Google will send you: http://code.google.com/apis/language/translate/v1/using_rest_translate.html
EDIT: Since free use of Google's API will be shut down on 2011-12-01, you could use Apertium. The call and response is almost the same: http://api.apertium.org/json/translate?q=hello%20world&langpair=en|es
回答2:
Another solution, is to wrap all calls in @pgratton's answer in only one call. Separate everything by using tags.
For example, put all contents of three textboxes in one string like this:
<t1>Desk</t1><t2>Monitor</t2><t3>Keyboard</t3>
And send it to the Google API. You will then get something like:
<t1>Secretária</t1><t2>Ecrã</t2><t3>Teclado</t3>
This is how you can save API calls. I've tried it almost two years ago and it was working then. You just need to make sure that the tags or whatever you're using to separate the fields are not translated and don't get lost in translation. The separators must be kept.
来源:https://stackoverflow.com/questions/7372231/how-can-i-use-google-translate-for-translating-values-in-a-website-form-field-t