ถ้าสมมุติว่าฟอร์มที่ส่งข้อมูลเดิมของเราเขียน
เราจะแปลงให้ส่งข้อมูลแบบ Ajax ได้โดย แก้เป็น
<form id="testF" method="post">…</form>
<script src="plus/jQuery/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$ () .ready (function () {
/*เริ่มทำงานเมื่อโหลดหน้าเสร็จ*/
$ ('#testF') .submit (function () {
/* ทำงานเมื่อฟอร์มไอดี testF โดนซับมิต*/
data=$ ('#testF') .serialize () /*ดึงค่าจากฟอร์มไอดี testF ทั้งหมด*/
$.post ('jQueryAjax.php' ,data ,function (response) {
/* รูปแบบคือ $.post (ไฟล์ปลายทาง ,ข้อมูล ,ฟังก์ชั่นที่จะทำเมื่อไฟล์ปลายทางตอบกลับมา) */
alert (response) ;
}) ;
return false;
}) ;
}) </script>
ตัวอย่าง
บันทึกเป็นไฟล์ชื่อ jQueryAjax.php
<?php
if ($_POST['iusername'] != '') {
echo 'ได้รับ ค่า iusername = '.$_POST['iusername']."\nipassword = ".$_POST['ipassword'];
exit () ;
}else{
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ส่งข้อมุลแบบ post ด้วย jQuery</title>
<script src="plus/jQuery/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$ () .ready (function () {alert ('12') ;
$ ('#testF') .submit (function () {
data=$ ('#testF') .serialize () $.post ('jQueryAjax.php' ,data ,function (response) {
alert (response) ;
}) ;
return false;
}) ;
}) </script>
</head>
<body>
<form id="testF" method="post">
<label for="iusername">รหัสผู้ใช้</label>
<input type="text" name="iusername">
<br>
<label for="ipassword">รหัสผ่าน</label>
<input type="password" name="ipassword">
<input type="submit" name="isubmit" value="ส่งข้อมูล">
</form>
</body>
</html>
<?php
}