2012-07-26 5 views
1

현재 MS Bing Translator 버전을 새로운 Azure 버전으로 변환하려고합니다. 새로운 문서 및 Microsoft에서 제공하는 (푸른 용) 다음 예제 있지만 설명 Microsoft Azure Translator AJAX API가 작동하지 않습니다.

내가 제대로 작동하는 액세스 토큰을 생성 :

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를 호출에 위의 코드를 변환하고 싶습니다.

나는 일 이전 버전에서 유사한 jQuery를 아약스 호출을 수정하지만, 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 그래서 당신의 시간 동안, 무슨 일이 잘못 이해합니다.

답변

1

다른 문제는 번역기에 대한 인증을위한 Bing AppID 메커니즘이 더 이상 사용되지 않는다는 것입니다. http://blogs.msdn.com/b/translation/p/gettingstarted2.aspx

권장 사항 :

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

여기 ASP.NET의 예는있다 :

마이크로 소프트는 여기에 윈도우 Azure 마켓 플레이스에서 번역기에 대한 액세스 권한을 얻기위한 과정을 자세히 설명하는 블로그 게시물을 Client ID와 Client Secret이 공개되지 않도록 ASP.NET, PHP, Node 또는 이와 비슷한 방식으로 토큰 서버 측을 가져 오기위한 코드를 작성해야합니다.

액세스 토큰을 얻은 후에는 서비스 호출의 HTTP 헤더에 해당 액세스 토큰을 기록해야합니다. ASP.NET 샘플에서는이를 보여 주며 JQuery에 적응하기가 상대적으로 쉽습니다.

+0

C#에서 새 액세스 토큰 메커니즘을 구현했습니다. 당신이 제공 한 두 번째 링크는 추구 할 보람있는 전략처럼 보입니다. 감사! –

0

호출에 jsonpCallback을 추가하고 새 기능을 정의 해 주실 수 있습니까? 이것은 jQuery 코드를 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!'); 
    } 
4

인증 토큰과 함께 Bing Translator를 사용하려면 먼저이 PHP 스크립트 token.php와 같은 서버 측 스크립트가 필요합니다. 웹 페이지의 자바 스크립트에서 매 9 분마다 호출됩니다.

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

존 DIMM에 의해 제출 된 스크립트를 시도하고 나를 위해 작동하지 않았다. 빈 상자와 상태 304 Not Modified를 반환합니다.대신 msdn 블로그에서이 링크 http://blogs.msdn.com/b/translation/p/phptranslator.aspx에있는 Microsoft 번역기 코드와 함께 PHP를 사용했으며 멋지게 작동했습니다.

관련 문제