2017-03-01 116 views
0

我想從英文翻譯我的輸入文本到泰米爾語。爲此,我使用了以下代碼片段。翻譯谷歌翻譯返回結果是百分比編碼

<form id="Master_form" class="form-horizontal"> 
    <div class="panel panel-default"> 
     <div class="panel-body" style="padding-top:6px;padding-bottom:2px"> 
      <div class="row" style="padding-bottom:15px"> 

       <div class="col-sm-4"> 
        <div class="form-group"> 
         <input id="enText" type="text" value=""> 
        </div> 
       </div> 
       <div class="col-sm-4"> 
        <div class="form-group"> 
         <input id="tnText" type="text" value=""> 
        </div> 
       </div> 
      </div> 
     </div> 
    </div> 
</form> 
<script> 
    $("#enText").keyup(function() { 
     var id = $('#enText').val(); 
     $.ajax({ 
      url: '@Url.Action("Foo", "Translate")', 
      type: 'GET', 
      dataType: 'json', 
      cache: false, 
      data: { 'id': id }, 
      success: function (result) { 
       //var res =unescapeUTF8EscapeSeq(result); 
       $('#tnText').val(res); 
      }, 
      error: function() { 
       alert('Error occured'); 
      } 
     }); 
    }); 

</script> 

和代碼背後,是

[HttpGet] 
     public JsonResult Foo(string id) 
     { 
      Translate trans = new Translate(); 
      trans.engText = ""; 
      trans.tmText = ""; 
      var langpair = "en%7Cta#en/ta/" + id; 
      string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", id, langpair); 
      WebClient webClient = new WebClient(); 
      webClient.Encoding = System.Text.Encoding.UTF8; 
      string result = webClient.DownloadString(url); 
      result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length); 
      result = result.Substring(result.IndexOf(">") + 1); 
      result = result.Substring(0, result.IndexOf("</span>")); 
      //result = UnescapeHex(result); 
      return Json(result.Trim(), JsonRequestBehavior.AllowGet); 
     } 

當我輸入SARA它返回的結果爲&#2970;&#3006;&#2992;&#3006;。 當它粘貼到谷歌它顯示翻譯文本。但在應用程序中它不會被轉換。

請提供您的寶貴意見,以解決這個問題。

回答

0

我通過綁定textarea中的值解決了這個問題,它顯示瞭解碼文本。

$("#" + src).keyup(function() { 
     //$("#" + src).change(function() { 
      var id = $('#' + src).val(); 
      $.ajax({ 
       url: '@Url.Action("Foo", "Translate")', 
       type: 'GET', 
       dataType: 'json', 
       cache: false, 
       data: { 'id': id }, 
       success: function (result) { 
        //var res =unescapeUTF8EscapeSeq(result); 
        //$('#tnText').val(res); 
        //$('#tnText').val(result); 
        $('#' + dest).val(decodeEntities(result)); 
       }, 
       error: function() { 
        alert('Error occured'); 
       } 
      }); 
     }) 


function decodeEntities(input) { 
    var y = document.createElement('textarea'); 
    y.innerHTML = input; 
    return y.value; 
}