javascript - Callback with Google Translate V2 - Stack Overflow

I used to use V1 of Google translate. In my JavaScript I would loop through a collection of elements af

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: "",
          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 = ';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.

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./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./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.

Share Improve this question asked Dec 22, 2011 at 12:02 SausageFingersSausageFingers 1,8465 gold badges34 silver badges54 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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./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>)

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./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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745271957a4619802.html

相关推荐

  • javascript - Callback with Google Translate V2 - Stack Overflow

    I used to use V1 of Google translate. In my JavaScript I would loop through a collection of elements af

    2小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信