API调用每个使用JS

huangapple go评论66阅读模式
英文:

API call for each using JS

问题

我正在使用Google API和JS点击外部来将第一个输入转换为目标语言。

我想从第一个输入中转换成多种语言,我已经添加了另一种目标语言——乌尔都语。

我需要这样的方式,当我在第一个框中输入内容时,它会同时转换成西班牙语和乌尔都语。

let $ = el => document.querySelector(el);

$('#input').addEventListener('keyup', function() {
  var text = this.value;
  doGet(text);
}, false);

function doGet(txt) {
  var sourceText = txt;  
  var sourceLang = 'en';
  var targetLang = $(".targee").value;
    
  var url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" 
            + sourceLang + "&tl=" + targetLang + "&dt=t&q=" + encodeURI(sourceText);
  
  $('.translated').value = 'LOADING...';
  var request = new XMLHttpRequest();
  request.open('GET', url, true);

  request.onload = () => {
    if (request.status >= 200 && request.status < 400) {
      // Success!
      let data = JSON.parse(request.responseText);
      let finaltext = '';
      for (let i = 0; i < data[0].length; i++) {
        finaltext += data[0][i][0];
      }
      $('.translated').value = finaltext;
    }
  };
  request.send();
}
h2, h3 {
  margin: 0 auto;
}
.boxes {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  max-width: 1000px;
  margin: 0 auto;
}
.box {
  width: 40%;
}

textarea {
  display: block;
  width: 100%;
  min-height: 160px;
  margin: 5px auto 20px;
  border-width: 2px;
  resize: none;
  
  &:focus {
    border: 2px solid black;
    outline: none;
  }
}
.btn-row {
  text-align: center;
  margin: 10px auto;
}
<div class="boxes">
  <div class="box">
    <h2>Input</h2>
    <input id="input">
  </div>
  
  <div class="box">
    <h2>Spanish</h2>
    <input value="es" class="targee">
    <input id="es" class="translated">
  </div>
  
  <div class="box">
    <h2>Urdu</h2>
    <input value="ur" class="targee">
    <input id="ur" class="translated">
  </div>
</div>
英文:

I am using Google API and JS click outside to convert the first input into targeted language.

I want to convert into multiple language from first input, I have added another Targeted language as URDU.

I need in such a way, when I give input in first box, it gets converted into Spanish as well as Urdu.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let $ = el =&gt; document.querySelector(el);

$(&#39;#input&#39;).addEventListener(&#39;keyup&#39;, function() {
  var text = this.value;
  doGet(text);
}, false);

function doGet(txt) {
  var sourceText = txt;  
  var sourceLang = &#39;en&#39;;
  var targetLang = $(&quot;.targee&quot;).value;
    
  var url = &quot;https://translate.googleapis.com/translate_a/single?client=gtx&amp;sl=&quot; 
            + sourceLang + &quot;&amp;tl=&quot; + targetLang + &quot;&amp;dt=t&amp;q=&quot; + encodeURI(sourceText);
  
  $(&#39;.translated&#39;).value = &#39;LOADING...&#39;;
  var request = new XMLHttpRequest();
  request.open(&#39;GET&#39;, url, true);

  request.onload = () =&gt; {
    if (request.status &gt;= 200 &amp;&amp; request.status &lt; 400) {
      // Success!
      let data = JSON.parse(request.responseText);
      let finaltext = &#39;&#39;;
      for (let i = 0; i &lt; data[0].length; i++) {
        finaltext += data[0][i][0];
      }
      $(&#39;.translated&#39;).value = finaltext;
    }
  };
  request.send();
}

<!-- language: lang-css -->

h2, h3 {
  margin: 0 auto;
}
.boxes {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  max-width: 1000px;
  margin: 0 auto;
}
.box {
  width: 40%;
}

textarea {
  display: block;
  width: 100%;
  min-height: 160px;
  margin: 5px auto 20px;
  border-width: 2px;
  resize: none;
  
  &amp;:focus {
    border: 2px solid black;
    outline: none;
  }
}
.btn-row {
  text-align: center;
  margin: 10px auto;
}

<!-- language: lang-html -->

  &lt;div class=&quot;boxes&quot;&gt;
    &lt;div class=&quot;box&quot;&gt;
      &lt;h2&gt;Input&lt;/h2&gt;
      &lt;input id=&quot;input&quot;&gt;
    &lt;/div&gt;
    
    &lt;div class=&quot;box&quot;&gt;
      &lt;h2&gt;Spanish&lt;/h2&gt;
      &lt;input value=&quot;es&quot; class=&quot;targee&quot;&gt;
      &lt;input id=&quot;es&quot; class=&quot;translated&quot;&gt;
    &lt;/div&gt;
    
    &lt;div class=&quot;box&quot;&gt;
      &lt;h2&gt;Urdu&lt;/h2&gt;
      &lt;input value=&quot;ur&quot; class=&quot;targee&quot;&gt;
      &lt;input id=&quot;ur&quot; class=&quot;translated&quot;&gt;
    &lt;/div&gt;
  
  &lt;/div&gt;

<!-- end snippet -->

答案1

得分: 2

如果您想要使用Google翻译API来进行多语言翻译,您可以循环向API URL发送请求。为了避免数据同步错误,您可以使用JavaScript的Promise和异步函数。

let $ = el => document.querySelector(el);
let $$ = el => document.querySelectorAll(el);

$('#input').addEventListener('keyup', function() {
  var text = this.value;
  doGet(text);
}, false);

async function doGet(txt) {
  var sourceText = txt;  
  var sourceLang = 'en';
  var targetLangs = $$(".targee");
  var request;
  var url; 
  
  for(var j = 0; j < targetLangs.length; j++) {
    url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" 
            + sourceLang + "&tl=" + targetLangs[j].value + "&dt=t&q=" + encodeURI(sourceText);
    $('.translated')[j].value = 'LOADING...';
    $('.translated')[j].value = await translate(url);
  }
}

async function translate(url) {
  return new Promise((resolve, reject) => {
    request = new XMLHttpRequest();
    request.open('GET', url, true);

    request.onload = () => {
      if (request.readyState == 4 && request.status >= 200 && request.status < 400) {
        // 请求成功!
        let data = JSON.parse(request.responseText);
        if(data[0]) {
          let finaltext = '';
          for (let i = 0; i < data[0].length; i++) {
            finaltext += data[0][i][0];
          };
          resolve(finaltext);
        } else {
          resolve('');
        }
      } else {
        // 错误!
        reject("error: " + request.statusText);
      }
    };
    request.send();
  });
}
h2, h3 {
  margin: 0 auto;
}
.boxes {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  max-width: 1000px;
  margin: 0 auto;
}
.box {
  width: 40%;
}

textarea {
  display: block;
  width: 100%;
  min-height: 160px;
  margin: 5px auto 20px;
  border-width: 2px;
  resize: none;
  
  &:focus {
    border: 2px solid black;
    outline: none;
  }
}
.btn-row {
  text-align: center;
  margin: 10px auto;
}
<div class="boxes">
  <div class="box">
    <h2>Input</h2>
    <input id="input">
  </div>
  
  <div class="box">
    <h2>Spanish</h2>
    <input value="es" class="targee">
    <input id="es" class="translated">
  </div>
  
  <div class="box">
    <h2>Urdu</h2>
    <input value="ur" class="targee">
    <input id="ur" class="translated">
  </div>
</div>
英文:

If you want to use the google translate API for multi-languages, you can loop the request to the API URL. To avoid errors in data synchronization, you can use Javascript Promise and async function.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let $ = el =&gt; document.querySelector(el);
let $$ = el =&gt; document.querySelectorAll(el);
$(&#39;#input&#39;).addEventListener(&#39;keyup&#39;, function() {
var text = this.value;
doGet(text);
}, false);
async function doGet(txt) {
var sourceText = txt;  
var sourceLang = &#39;en&#39;;
var targetLangs = $$(&quot;.targee&quot;);
var request;
var url; 
for(var j = 0; j &lt; targetLangs.length; j++) {
url = &quot;https://translate.googleapis.com/translate_a/single?client=gtx&amp;sl=&quot; 
+ sourceLang + &quot;&amp;tl=&quot; + targetLangs[j].value + &quot;&amp;dt=t&amp;q=&quot; + encodeURI(sourceText);
$$(&#39;.translated&#39;)[j].value = &#39;LOADING...&#39;;
$$(&#39;.translated&#39;)[j].value = await translate(url);
}
}
async function translate(url) {
return new Promise((resolve, reject) =&gt; {
request = new XMLHttpRequest();
request.open(&#39;GET&#39;, url, true);
request.onload = () =&gt; {
if (request.readyState == 4 &amp;&amp; request.status &gt;= 200 &amp;&amp; request.status &lt; 400) {
// Success!
let data = JSON.parse(request.responseText);
if(data[0]) {
let finaltext = &#39;&#39;;
for (let i = 0; i &lt; data[0].length; i++) {
finaltext += data[0][i][0];
};
resolve(finaltext);
} else {
resolve(&#39;&#39;);
}
} else {
// Error!
reject(&quot;error: &quot;+request.statusText);
}
};
request.send();
});
}

<!-- language: lang-css -->

h2, h3 {
  margin: 0 auto;
}
.boxes {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  max-width: 1000px;
  margin: 0 auto;
}
.box {
  width: 40%;
}

textarea {
  display: block;
  width: 100%;
  min-height: 160px;
  margin: 5px auto 20px;
  border-width: 2px;
  resize: none;
  
  &amp;:focus {
    border: 2px solid black;
    outline: none;
  }
}
.btn-row {
  text-align: center;
  margin: 10px auto;
}

<!-- language: lang-html -->

  &lt;div class=&quot;boxes&quot;&gt;
    &lt;div class=&quot;box&quot;&gt;
      &lt;h2&gt;Input&lt;/h2&gt;
      &lt;input id=&quot;input&quot;&gt;
    &lt;/div&gt;
    
    &lt;div class=&quot;box&quot;&gt;
      &lt;h2&gt;Spanish&lt;/h2&gt;
      &lt;input value=&quot;es&quot; class=&quot;targee&quot;&gt;
      &lt;input id=&quot;es&quot; class=&quot;translated&quot;&gt;
    &lt;/div&gt;
    
    &lt;div class=&quot;box&quot;&gt;
      &lt;h2&gt;Urdu&lt;/h2&gt;
      &lt;input value=&quot;ur&quot; class=&quot;targee&quot;&gt;
      &lt;input id=&quot;ur&quot; class=&quot;translated&quot;&gt;
    &lt;/div&gt;
  
  &lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月6日 05:09:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定