Domanda

Sto cercando di convertire dalla versione corrente del traduttore MS Bing al nuovo Azure One.

Ho creato un token di accesso come descritto nella nuova documentazione e sebbene il seguente esempio (per Azure) fornito da Microsoft funziona correttamente:

function translate() {

  var from = "en", to = "es", text = "hello world";
  var s = document.createElement("script");
  s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate" +
            "?appId=" + settings.appID +
            "&from=" + encodeURIComponent(from) +
            "&to=" + encodeURIComponent(to) +
            "&text=" + encodeURIComponent(text) +
            "&oncomplete=mycallback";
  document.body.appendChild(s);
}

function mycallback(response) {
  alert(response); 
}
.

Vorrei convertire il codice sopra per una chiamata jQuery.

Ho modificato una chiamata jQuery Ajax simile dalla versione precedente che ha funzionato, ma viene emesso un parseerror-jQuery17206897480448242277_1343343577741 was not called:

  function jqueryTranslate() {
    var p = {};
    p.appid = settings.appID;
    p.to = "es";
    p.from = "en";
    p.text = "Goodbye Cruel World";
    p.contentType = 'text/html';
    $.ajax({
      url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
      data: p,
      dataType: 'jsonp',
      jsonp: 'oncomplete',
      complete: function (request, status) {
      },
      success: function (result, status) {
        alert(result);
      },
      error: function (a, b, c) {
        alert(b + '-' + c);
      }
    });
  }
.

Apprezzerei molto e la comprensione di ciò che sta andando male, quindi Tia per il tuo tempo.

È stato utile?

Soluzione

L'altro problema è che il meccanismo APPID Bing per l'autenticazione contro il traduttore è stato deprecato.

Microsoft ha un post sul blog in dettaglio del processo per ottenere l'accesso al traduttore nel Marketplace di Windows Azure qui:

http://blogs.msdn.com/b/translation/p/getingstarted1.aspx

C'è un esempio in ASP.NET qui: http://blogs.msdn.com/b/translation/p/getingstated2.aspx

La raccomandazione è (almeno) per inserire il tuo codice per ottenere il lato del server token in ASP.NET, PHP, nodo o qualcosa di simile in modo che l'ID cliente e il segreto del cliente non siano esposti.

Una volta ottenuto il token di accesso, deve essere scritto negli intestazioni HTTP della chiamata al servizio.Il campione ASP.NET mostra che, e dovrebbe essere relativamente facile adattarsi alle jQuery.

Altri suggerimenti

Per utilizzare il traduttore Bing con token di autenticazione, è necessario prima necessità uno script sul lato server come questo script PHP, token.php.Sarà chiamato ogni 9 minuti dal JavaScript sulla tua pagina web.

<?php
$ClientID="your client id";
$ClientSecret="your client secret";

$ClientSecret = urlencode ($ClientSecret);
$ClientID = urlencode($ClientID);

// Get a 10-minute access token for Microsoft Translator API.
$url = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
$postParams = "grant_type=client_credentials&client_id=$ClientID&client_secret=$ClientSecret&scope=http://api.microsofttranslator.com";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);  
$rsp = curl_exec($ch); 

print $rsp;
?>
.

Quindi questa pagina HTML visualizzerà un'interfaccia a due caselle che si traduce dall'inglese al francese.

Nota: una versione precedente di questo post mancava le prime 5 linee e quindi non è riuscita a caricare jQuery.(Ci scusiamo per quello @ db1.) Lo script di lavoro è online qui:

http://www.johndimm.com/bricacns/

<html>

<head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

  <script language="javascript">
    var g_token = '';

    function onLoad() {
      // Get an access token now.  Good for 10 minutes.
      getToken();
      // Get a new one every 9 minutes.
      setInterval(getToken, 9 * 60 * 1000);
    }

    function getToken() {
      var requestStr = "/bingtrans/token.php";

      $.ajax({
        url: requestStr,
        type: "GET",
        cache: true,
        dataType: 'json',
        success: function (data) {
          g_token = data.access_token;
        }
      });
    }

    function translate(text, from, to) {
      var p = new Object;
      p.text = text;
      p.from = from;
      p.to = to;
      p.oncomplete = 'ajaxTranslateCallback'; // <-- a major puzzle solved.  Who would have guessed you register the jsonp callback as oncomplete?
      p.appId = "Bearer " + g_token; // <-- another major puzzle.  Instead of using the header, we stuff the token into the deprecated appId.
      var requestStr = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate";

      window.ajaxTranslateCallback = function (response) {
        // Display translated text in the right textarea.
        $("#target").text(response);
      }

      $.ajax({
        url: requestStr,
        type: "GET",
        data: p,
        dataType: 'jsonp',
        cache: true
      });
    }


    function translateSourceTarget() {
      // Translate the text typed by the user into the left textarea.
      var src = $("#source").val();
      translate(src, "en", "fr");
    }
  </script>
  <style>
    #source,
    #target {
      float: left;
      width: 400px;
      height: 50px;
      padding: 10px;
      margin: 10px;
      border: 1px solid black;
    }
    #translateButton {
      float: left;
      margin: 10px;
      height: 50px;
    }
  </style>
</head>

<body onload="onLoad();">

  <textarea id="source">Text typed here will be translated.</textarea>
  <button id="translateButton" onclick="translateSourceTarget();">Translate English to French</button>
  <textarea id="target"></textarea>

</body>

</html>
.

Potresti provare ad aggiungere un jsonpcallback alla tua chiamata e definire una nuova funzione per questo.Questo è ciò che sembra mancare quando confronto il tuo codice jQuery con l'esempio da Microsoft.

  function jqueryTranslate() {
    var p = {};
    p.appid = settings.appID;
    p.to = "es";
    p.from = "en";
    p.text = "Goodbye Cruel World";
    p.contentType = 'text/html';
    $.ajax({
      url: 'http://api.microsofttranslator.com/V2/Ajax.svc/Translate',
      data: p,
      dataType: 'jsonp',
      jsonp: 'oncomplete',
      jsonpCallback: 'onCompleteCallback',   <------------------ THIS LINE
      complete: function (request, status) {
      },
      success: function (result, status) {
        alert(result);
      },
      error: function (a, b, c) {
        alert(b + '-' + c);
      }
    });
  }

  function onCompleteCallback(response) {    <------------------- THIS FUNCTION
    alert('callback!'); 
  }
.

ha provato lo script inviato da John Dimm e non ha funzionato per me.Restituisce una casella vuota e uno stato 304 non modificato.Invece ho usato il PHP con Microsoft Translator Code presso il Blog MSDN su questo link http://blogs.msdn.com/b/translation/p/phptranslator.aspx e ha funzionato magnificamente

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top