Microsoft Azure转换器AJAX API不工作



我正在尝试从当前版本的微软必应翻译转换到新的Azure版本。

我创建了一个访问令牌,如新文档中所述,尽管微软提供的以下示例(针对Azure)工作正常:

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

我想把上面的代码转换成一个jQuery调用。

我修改了以前版本中类似的jQueryajax调用,该调用有效,但发出了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);
      }
    });
  }

我将非常感谢和理解出了什么问题,所以TIA为您的时间。

要使用带有身份验证令牌的Bing Translator,首先需要一个服务器端脚本,如PHP脚本token.PHP。它将每9分钟从网页上的javascript调用一次。

<?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;
?>

然后这个html页面将显示一个从英语翻译成法语的两框界面。

注意:这篇文章的早期版本缺少前5行,因此无法加载jQuery。(很抱歉@db1。)工作脚本在线:

http://www.johndimm.com/bingtrans/

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

另一个问题是针对翻译器进行身份验证的Bing-AppID机制已被弃用。

微软有一篇博客文章详细介绍了在Windows Azure Marketplace中访问翻译器的过程:

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

这里有一个ASP.NET示例:http://blogs.msdn.com/b/translation/p/gettingstarted2.aspx

建议(至少)将获取令牌服务器端的代码放在ASP.NET、PHP、Node或类似的代码中,这样就不会暴露客户端ID和客户端机密。

一旦获得了访问令牌,就需要将其写入到服务调用的HTTP头中。ASP.NET示例显示了这一点,并且应该比较容易适应JQuery。

你能试着在调用中添加一个jsonpCallback并为它定义一个新函数吗?当我将你的jQuery代码与微软的示例进行比较时,这似乎是缺失的。

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

尝试了John Dimm提交的脚本,但它对我不起作用。返回一个空白框和状态304"未修改"。相反,我在msdn博客的这个链接上使用了带有Microsoft翻译代码的PHPhttp://blogs.msdn.com/b/translation/p/phptranslator.aspx它的运行得很好

最新更新