忍者ブログ

からすまる日誌

20200110 php ajax ver01

×

[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。

20200110 php ajax ver01

ver.1:
 
--->test2.html
 
<!DOCTYPE html>
<html lang="ja">
 <head>
  <meta charset="UTF-8">
  <title>データベースとの連携</title>
  <link rel="stylesheet" href="test1.css">
  <script src="../jquery-3.4.1.min.js"></script>
 </head>
 <body>
  <p>表示ボタンを押せ</p>
  <p><button id="btn">表示</button></p>  
  <h1>メニュー一覧</h1>
  <ul id="menu"></ul>
  
  <script src="test2.js"></script>  
 </body>
</html>
 
--->test1.css
 
body{
 background:#feffab;
 background-image:url(../fish_kue2.png);
 /*background-repeat: no-repeat;*/
}
select{
 height:3rem;
}
 
--->test2.js
 
$(function(){
 $('#btn').on('click',function(){
  //Ajax通信の実行
  $.ajax({
   url:'../lunch_api2.php',
   type:'get',
   dataType:'json'
  })
  .done(function(data){//成功
   console.log(data);
   //console.log(data[0]);
   
   $('#menu').empty();
   $('#menu').css('opacity',0);
   for (i=0; i<data.length; i++){
    var ele = $('<li>').text(data[i].menu);
    $('#menu').append(ele);  
   } 
   $('#menu').animate({'opacity':1},1000);
  })
  .fail(function(){//失敗
   alert("fail");
  });
  
 });
});
 
--->lunch_api2.php
 
<?php
$user = "root";
$pass = "";
$host = "localhost";
$dbname = "lunch";
$dsn = "mysql:host={$host};dbname={$dbname};charset=utf8";
$pdo = new PDO($dsn, $user, $pass);
$res = $pdo->query("SELECT * FROM foods");
$rows = $res->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($rows);
echo $json;
?>
 
 
PR

コメント

ブログ内検索

カレンダー

04 2025/05 06
S M T W T F S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31