使用 Google Translate V2 进行回调

发布于 2024-12-22 11:55:28 字数 1642 浏览 3 评论 0原文

我以前用的是谷歌翻译V1。在我的 JavaScript 中,我会在页面加载后循环遍历元素集合,翻译文本并将结果输出到相应的文本框中。我正在努力在付费 API V2 中实现相同的功能(启用计费)。

这就是我在 V1 中在循环中所做的:

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

这很有效,因为回调函数嵌入在请求中,因此一旦结果返回,我就可以更新正确元素的内部文本。

在 V2 中似乎没有类似的方法。我尝试使用 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');
                 }
          });

我可以让 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);
            }

如果我可以将额外的参数传递到回调函数中,那么我可以指定要更新的控件,但我认为使用此方法不可能做到这一点。

I used to use V1 of Google translate. 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. Im struggling to implement the same functionality in the V2 of the paid API (billing is enabled).

This is what I did in V1, inside a loop:

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.

In V2 there doesn't appear to be a like for like method. 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:

  $.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:

 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

早乙女 2024-12-29 11:55:28

那么,您可以为正在翻译的每个元素创建一个“新”回调函数,并在完成后删除该函数。即:

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);
}

然后对于每个元素,您可以调用 translateElement()

Well, you can create a 'new' callback function for every element you are translating, and remove the function once done. i.e. 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>)

暮年慕年 2024-12-29 11:55:28

成功!

我设法使 $.ajax() 方法正常工作,这使我能够为每个单独的翻译元素创建一个回调函数。

第一个问题是我使用的是 jQuery 1.4.x。 1.5 版及以上版本允许使用 JASONP 数据类型时跨域调用。这就是为什么我收到“访问被拒绝”消息的原因。

第二个更改是将 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');
                 }
          });

希望这对其他人有用。

Success!

I managed to make the $.ajax() method work, which allowed me to create a callback function for each individual translated element.

First problem was that I was using jQuery 1.4.x. Version 1.5 onwards allows cross domain calls when using JASONP datatype. This was why I was getting the "Access is denied" message.

Second change was to change the dataType from jspn to 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文