Ajax 在 HTML 裡可以不透過 Html Form 元件來傳遞資料到後端的 PHP,再處理或寫入資料庫
第一份 001.html,透過 Ajax 傳遞 Form 表單
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <title>001 使用 Ajax 傳遞 form 表單</title> </head> <body> <form id="form" action="" method="post"> Name: <input type="text" name="name"><br> Age: <input type="text" name="age"><br> FavColor: <input type="text" name="favcolor"><br> <input id="submit" type="button" name="submit" value="submit"> </form> <script> $(document).ready(function(){ $("#submit").on('click', function(){ $.ajax({ url: '001.php', type : "POST", dataType : 'json', data : $("#form").serialize(), success : function(result) { console.log(result); }, error: function(result) { console.log(result); } }) }); }); </script> </body> </html>
第二份 001.html,透過 Ajax 傳遞資料,此結構並沒有用 Form
直接透過 a tag 來傳遞事件到 JS,並在 JS 裡取得該欄位資料
這個範例的 js 裡 input 的資料並沒有實際去取得,純綷測試用,要注意
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <title>002 不使用 form 也是可以直接用 Ajax 傳到 PHP 的</title> </head> <body> Name: <input type="text" id="name1" name="name1"><br> Age: <input type="text" id="age1" name="age1"><br> FavColor: <input type="text" id="favcolor1" name="favcolor1"><br> <a href="#" onclick="$.fn.insertData(1)" />新增<a/> <br /><br /><br /> Name: <input type="text" id="name2" name="name2"><br> Age: <input type="text" id="age2" name="age2"><br> FavColor: <input type="text" id="favcolor2" name="favcolor2"><br> <a href="#" onclick="$.fn.insertData(2)" />新增<a/> <script> $(document).ready(function(){ $.fn.insertData = function(id){ if(id == 1) { var person = {name:'小黑',age: 26,favcolor: '黑色'}; } else { var person = {name:'小黑2',age: 27,favcolor: '黑色2'}; } $.ajax({ url: '001.php', type : "POST", dataType : 'json', data : person, success : function(result) { console.log(result); }, error: function(result) { console.log(result); } }) } }); </script> </body> </html>
建立一個 PHP 檔案,接受 001.html 或 002.html 所傳過來的值,並寫入資料庫並回傳一個字串 success 或 failed 文字,可以使用 Google Chrome WebDev TOOLS 來觀察這個回傳的文字資料
<?php $data = $_POST; $dbhost = 'localhost'; $dbuser = 'bentest'; $dbpasswd = '1234'; $dbname = 'bentest'; $dsn = "mysql:host=".$dbhost.";dbname=".$dbname; try { //注意,使用 PDO 方式連結,需要指定一個資料庫,否則將拋出異常 $conn = new PDO($dsn,$dbuser,$dbpasswd); $conn->exec("SET CHARACTER SET utf8"); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: ".$e->getMessage(); } $sql = "INSERT INTO `001`(name, age, favcolor) VALUES(:name, :age, :favcolor)"; $dataArr = array( ':name' => $data['name'], ':age' => $data['age'], ':favcolor' => $data['favcolor']); try { //這個步驟返回一個物件,裡面有 SQL 語法,返回有可能為空屬性或錯的 SQL,但不檢查不報錯 $sth = $conn->prepare($sql); if($sth) { //直到這個步驟才會執行 SQL 語法,返回 bool(true) $result = $sth->execute($dataArr); if($result)//true or false { $result = 'success'; echo json_encode($result); return; } else { $result = 'failed'; echo json_encode($result); return; } } } catch(PDOException $e) { echo "執行預存程序失敗. ".$e->getMessage(); } ?>