简体   繁体   English

使用Google翻译V2进行回调

[英]Callback with Google Translate V2

I used to use V1 of Google translate. 我曾经使用Google翻译的V1。 In my JavaScript I would loop through a collection of elements after the page had loaded, translate the text and output the result into a corresponding text box. 在我的JavaScript中,页面加载后,我将遍历元素集合,翻译文本并将结果输出到相应的文本框中。 Im struggling to implement the same functionality in the V2 of the paid API (billing is enabled). 我难以在付费API的V2中实现相同的功能(已启用计费功能)。

This is what I did in V1, inside a loop: 这是我在V1中的循环内所做的:

google.language.translate(lookupText, 'gb', 'fr', function (result) {
if (!result.error) {
ctlSuggestion.innerText = result.translation;
}
});

This worked well because the callback function was embedded in the request, so I could update the innerText of the correct element once the result came back. 这很有效,因为回调函数已嵌入请求中,所以一旦返回结果,我就可以更新正确元素的innerText。

In V2 there doesn't appear to be a like for like method. 在V2中,似乎没有类似方法。 I tried using jQuery Ajax but I got an "Access is denied" message, I think this is because its a cross domain call or something: 我尝试使用jQuery Ajax,但收到“拒绝访问”消息,我认为这是因为它是跨域调用或其他原因:

  $.ajax({
          type: "GET",
          url: "https://www.googleapis.com/language/translate/v2",
          data: { key: "API-KEY", source: "en", target: "fr", q: lookupText },
          dataType: 'json',
          success: function (data) {
                     alert(data.data.translations[0].translatedText);
                    },
          error: function (data) {
                   alert('fail');
                 }
          });

I can get the REST method to work, but in the callback function there is no way of knowing what control the request came from: 我可以使用REST方法,但是在回调函数中,无法知道请求来自哪个控件:

 var newScript = document.createElement('script');
            newScript.type = 'text/javascript';
            var sourceText = "Hello World"
            var source = 'https://www.googleapis.com/language/translate/v2?key=API-KEY=en&target=de&callback=translateText&q=' + sourceText;
            newScript.src = source;

            // When we add this script to the head, the request is sent off.
            document.getElementsByTagName('head')[0].appendChild(newScript);


            function translateText(response) {
                alert(response.data.translations[0].translatedText);
            }

If I could pass an extra parameter into the callback function then I could specify the control to update, but I don't think this is possible using this method. 如果我可以将一个额外的参数传递给回调函数,则可以指定要更新的控件,但是我认为使用此方法是不可能的。

Well, you can create a 'new' callback function for every element you are translating, and remove the function once done. 好了,您可以为要翻译的每个元素创建一个“新”回调函数,并在完成后删除该函数。 ie Something like: 即类似的东西:

function translateElement(elementID) {

    var element = document.getElementsById(elementID);

    // this is a temporary function for updating this particular element
    window['translate'+elementID] = function(response) {
        document.getElementsById(elementID).innerHTML = response.data.translations[0].translatedText;
        setTimeout(function() {
            // remove the temporary function
            window['translate'+elementID] = null;
        }, 1000);
    };

    var newScript = document.createElement('script');
    newScript.type = 'text/javascript';
    var sourceText = "Hello World"
    var source = 'https://www.googleapis.com/language/translate/v2?key=API-KEY=en&target=de&'+
    'callback=translate'+elementID+'&q=' + sourceText;
    newScript.src = source;

    // When we add this script to the head, the request is sent off.
    document.getElementsByTagName('head')[0].appendChild(newScript);
}

Then for each element you can call translateElement(<id>) 然后,对于每个元素,您可以调用translateElement(<id>)

Success! 成功!

I managed to make the $.ajax() method work, which allowed me to create a callback function for each individual translated element. 我设法使$.ajax()方法起作用,这使我能够为每个翻译后的元素创建一个回调函数。

First problem was that I was using jQuery 1.4.x. 第一个问题是我使用的是jQuery1.4.x。 Version 1.5 onwards allows cross domain calls when using JASONP datatype. 从1.5版开始,使用JASONP数据类型时可以进行跨域调用。 This was why I was getting the "Access is denied" message. 这就是为什么我收到“访问被拒绝”消息的原因。

Second change was to change the dataType from jspn to jsonp : 第二个更改是将dataTypejspn更改为jsonp

$.ajax({
          type: "GET",
          url: "https://www.googleapis.com/language/translate/v2",
          data: { key: "API-KEY", source: "en", target: "fr", q: lookupText },
          dataType: 'jsonp',
          success: function (data) {
                     alert(data.data.translations[0].translatedText);
                    },
          error: function (data) {
                   alert('fail');
                 }
          });

Hope this is of some use to others. 希望这对其他人有用。

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

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