jQuery 提供了 $.post() 這個語法糖,用 POST 方式發送非同步請求。
jQuery.post(url, [data], [callback], [type])
json、xml、html、text、script 等。<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script language="javascript">
function checkemail() {
if ($('#email').val() == "") {
$('#msg').html("please enter the email!");
$('#email').focus();
return false;
}
if ($('#address').val() == "") {
$('#msg').html("please enter the address!");
$('#address').focus();
return false;
}
ajax_post();
}
function ajax_post() {
$.post("action.php",
{ email: $('#email').val(), address: $('#address').val() },
function (data) {
$('#msg').html(data);
},
"text" // 回應型別可為 json、html、xml、text
);
}
</script>
</head>
<body>
<form id="ajaxform" name="ajaxform" method="post" action="action.php">
<p>email<input type="text" name="email" id="email" /></p>
<p>address<input type="text" name="address" id="address" /></p>
<p id="msg"></p>
<p><input name="Submit" type="button" value="submit" onclick="return checkemail()" /></p>
</form>
</body>
</html>
<?php $email = $_POST["email"]; $address = $_POST["address"]; echo "success"; ?>
注意按鈕的 type 是 button 而非 submit。差別在於:
type="submit":按下時瀏覽器會直接把表單資料以 POST 送到 action 指定的頁面,整個頁面跳轉。type="button" + $.post():按下時只觸發 JS 函式,由 ajax_post() 在背景以 POST 送出資料,頁面不跳轉。這正是「 Ajax 」與「傳統表單提交」在行為上的分野。
function(data, textStatus, jqXHR),能取得狀態文字與 XHR 物件。$.post(...).fail(function (xhr, status, err) { ... }),或在 $.ajaxSetup 中設定全域的 error。htmlspecialchars() 轉義,避免 XSS。理解 $.post() 之後,$.get() 的用法完全相同,只是把方法名換掉即可。