0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScriptだけで無料翻訳APIを呼ぶ最小サンプル(MyMemory+fetch+async/await)

Posted at

1. MyMemory API とは?


2. 最小構成サンプル

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>翻訳ミニサンプル</title>
</head>
<body>
  <textarea id="src" rows="3" cols="40">Hello, world!</textarea><br>
  <button id="btn">翻訳する</button>
  <p id="dst"></p>

  <!-- たった1本の ES Module で完結 -->
  <script type="module">
    // 1) ボタンクリックを監視
    document.getElementById('btn').onclick = async () => {
      // 2) 入力取得
      const text = document.getElementById('src').value.trim();
      // 3) 翻訳中表示
      document.getElementById('dst').textContent = '…翻訳中…';

      // 4) MyMemory API URL を組み立て
      const url = `https://api.mymemory.translated.net/get?q=${encodeURIComponent(text)}&langpair=en|ja`;
      // 5) fetch で HTTP GET(await で完了を待つ)
      const res = await fetch(url);
      // 6) レスポンスを JSON に変換
      const data = await res.json();
      // 7) 結果を取り出し
      const jp = data.responseData.translatedText || '(翻訳失敗)';
      // 8) 画面に表示
      document.getElementById('dst').textContent = jp;
    };
  </script>
</body>
</html>

補足. async / await って?

  • async を付けた関数は Promise を返す
  • await を付けると、Promise が解決するまで 同期的に待って結果を受け取れる
  • コールバック地獄 (then().then()…) を回避できる

補足.補足:translatedText プロパティは公式レスポンスに含まれる

MyMemory の REST API に q(翻訳したい文)と langpair=en|ja を付けて GET すると、
JSON 形式 で下記のようなデータが返ります。


{
  "responseData": {
    "translatedText": "こんにちは 世界"
  },
  "responseStatus": 200,
  ...
}

responseData オブジェクトの中に translatedText が入っているのがポイントです。

公式仕様書にも「/responseData/translatedText が返る」と記載があります。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?