LoginSignup
7
8

More than 5 years have passed since last update.

【JavaScript】Ajax(非同期通信)でAPIと通信する(要jQuery)

Last updated at Posted at 2018-02-20

Ajax(非同期)を使ってAPIと通信したい

ボタンを押すたびに非同期でAPIに値を送信したいときあるかもしれません。ぼくはいまのところないです。
したいときあるかなーと思って書いてみたので残しておきます。

例によってPOST送信するAPIはこれ→【PHP】とりあえずAPIのスタブをパパっと作る - Qiita

AjaxでPOSTする実装

お前いつもjQueryつかってんなていわれるかもしれませんが許してください。

post.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>AjaxAPI</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script type="text/javascript">

        function sendPostToApiByAjax()
        {
            $.ajax({
                type:     "POST",
                url:      "https://*******************/api.php",
                // username: "*****", // Basic認証用ユーザー名
                // password: "*****", // Basic認証用パスワード
                data: {
                    name : 'ajaxAPI' // リクエストパラメータ
                },
                xhrFields: {
                    withCredentials: true
                },

            }).done(function(data) {

                console.log('Successful communication with API!');

                console.log('ReturnParameter:' + data['name']);

            }).fail(function(data) {
                console.log('Ajax fail (communication error)');
            });
        }

        </script>
    </head>
    <body>
        <button type="button" name="post" onclick="sendPostToApiByAjax();">非同期POST</button>
    </body>
</html>

スタブAPI に対してPOSTした際に吐き出されるlogはこんな感じ↓

log.txt
【→API】RequestParameter:ajaxAPI'
【←API】ReturnParameter :{"name":"ajaxAPI_RECEIVED","date":"2018-02-19 13:41:26"}
----------

おわり

  • クロスドメイン問題やらがむずかしいすね。
  • スタブAPI にはAccess-Control-Allow-Originを記述してます。
  • なにかご指摘あればお願いいたします。

参考

などなど

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