LoginSignup
15

More than 5 years have passed since last update.

API取得PHPプログラム

Posted at

api/index.html

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>WebAPI test</title>
</head>
<body>
  <h2>WebAPI</h2>
  <h3>リクエスト</h3>
  <!-- ユーザタイプを入力するテキストボックス -->
  User Type:<input type="text" name="dataType" /><br>
  <!-- 入力する値の項目 -->
  <ul>
    <li>a:Admin</li>
    <li>o:Operator</li>
    <li>g:Guest</li>
    <li>e:Empty</li>
  </ul>
  <!-- ajax()を実行するボタン -->
  <button data-btn-type="ajax">Data get!</button>
  <br><br>
  <h3>結果</h3>
  <!-- 結果表示用のdivタグ -->
  <div data-result="">未取得</div>
  <script src="../lib/jquery.js"></script>
  <script type="text/javascript" src="api.js"></script>
  <!-- <script type="text/javascript" src="api2.js"></script> -->
</body>
</html>



api/api/users.php

users.php

<?php
function returnJson($resultArray){
  if(array_key_exists('callback', $_GET)){
    $json = $_GET['callback'] . "(" . json_encode($resultArray) . ");";
  }else{
    $json = json_encode($resultArray);
  }
  header('Content-Type: text/html; charset=utf-8');
  echo  $json;
  exit(0);
}


//---------------------------------------------------------
//  処理の開始
//---------------------------------------------------------
//  値の取得(リクエストの受付)
$type = $_REQUEST["user_type"];

//  ユーザリストの初期化
$user_list = [];
//  返却値の初期化
$result = [];

try {
  //  値の検証
  if (empty($type)) {
    throw new Exception("no type...");
  }

  //  ユーザリストの作成
  switch ($type) {
    case 'a':
    case 'admin':
      $user_list = [
        ['name'=>'中居','age'=>18]
      ];
      break;
    case 'o':
    case 'operator':
      $user_list = [
        ['name'=>'木村','age'=>17],
        ['name'=>'森','age'=>16]
      ];
      break;
    case 'g':
    case 'guest':
      $user_list = [
        ['name'=>'香取','age'=>14],
        ['name'=>'草薙','age'=>15],
        ['name'=>'稲垣','age'=>15],
        ['name'=>'岡田','age'=>15],
        ['name'=>'森田','age'=>15],
        ['name'=>'三宅','age'=>15],
        ['name'=>'長野','age'=>15],
        ['name'=>'坂本','age'=>15],
        ['name'=>'井ノ原','age'=>15]
      ];
      break;
    default:
      //  不正な値
      throw new Exception("Invalid value...");
      break;
  }

  //  返却値の作成
  $result = [
    'result' => 'OK',
    'users' => $user_list
  ];
} catch (Exception $e) {
  $result = [
    'result' => 'NG',
    'message' => $e->__toString()
  ];
}

//  JSONでレスポンスを返す
returnJson($result);
?>



api/api.js

api.js

$(function() {
  //  クリックイベントにajax処理を登録する
  $('body').on('click', 'button[data-btn-type=ajax]', function(e) {
    console.log('click btn');
    //  リクエストの下準備
    //  リクエスト時に一緒に送るデータの作成
    var send_data;
    send_data = {
      //  テキストボックスの値を設定
      user_type : $('input').val()
    };
    console.log(send_data);
    //  WebAPIを叩く
    $.ajax({
      //  リクエストの内容
      type: "POST",
      url: 'api/users.php',
      dataType: "json",
      data: send_data,
      //  レスポンス成功時の処理
      success: function(responce) {
        if (responce.result === "OK") {
          console.log("成功1");
          console.log(responce);
          $('div[data-result=""]').html(JSON.stringify(responce));
        } else {
          console.log("成功2");
          console.log(responce);
          $('div[data-result=""]').html(JSON.stringify(responce));
        }
        return false;
      },
      //  レスポンス失敗時の処理
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log("エラー");
        console.log(XMLHttpRequest);
        console.log(textStatus);
        console.log(errorThrown);
        $('div[data-result=""]').html(JSON.stringify("データ取得中にエラーが発生しました。"));
        return false;
      }
    });
    //  フォーカスをテキストボックスに合わせる
    $('input').focus();

    return false;
  });
});


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
15