LoginSignup
15
14

More than 3 years have passed since last update.

PHPで自作APIを作り、axiosでデータを取ってきて表示する

Last updated at Posted at 2019-05-25

phpで自作APIを作り、そのデータをaxiosを使って検索して取ってくるというものを作ります。
完成イメージ↓
ezgif.com-video-to-gif.gif

まずはhtmlです。

  <input type="text" class="input">
  <div class="result"></div>

  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="./app.js"></script>

(axios→https://github.com/axios/axios)

inputに入力された値に応じて結果を表示します。

jsでは入力されるたびにaxiosで通信する処理をします。


document.querySelector('.input').addEventListener('keyup', function() {

  // 結果表示の要素を取得
  const result = document.querySelector('.result');

  // 入力が空だったら結果表示を空にして処理を止める
  if(!this.value) return result.textContent = '';

  // パラメータの指定
  let params = new URLSearchParams();
  params.append('input_val', this.value);

  axios.post('./api.php', params).then(response => {
    result.textContent = response.data.text; // 結果の文字列を表示する
    result.style.color = response.data.color; // 結果の色を適用する
  }).catch(error => {
    // エラーを受け取る
    console.log(error);
  });
});

パラメータの指定について→https://qiita.com/taroc/items/f22f7dd5d6d5443c72a4

通信先のapi.phpでは、送られてきた値によって出力するデータを決める処理をしています。

<?php
// 検索対象の配列
$data = ['kyuri', 'gobo', 'tomato', 'ninjin', 'toufu'];

if(empty($_POST['input_val'])){
  exit(); // POSTが空だったら終了する
}

// 出力する配列を作る関数
function createResponse($val, $isIn){
  $result = [
    'text' => $isIn ? $val.' あるよ!' : $val.'はないよ...', // 第2引数の$isInがtrueかfalseかで内容を変える
    'color' => $isIn ? 'red' : 'blue' // 第2引数の$isInがtrueかfalseかで赤か青かを決める
  ];
  return $result;
};

// POSTされた入力内容の値を変数に格納
$inputValue = $_POST['input_val'];

// in_arrayで入力内容の値が配列に存在するか調べる
if(in_array($inputValue, $data)){

  // 存在する場合第2引数をtrueにしてcreateResponse関数を呼び出し、出力する
  echo json_encode(createResponse($inputValue, true));
  exit();

}else{

  // 存在しない場合第2引数をfalseにしてcreateResponse関数を呼び出し、出力する
  echo json_encode(createResponse($inputValue, false));
  exit();

}

json_encodeも忘れずに!

15
14
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
15
14