您可以使用这样的 HTML 表单:
<html>
<head>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.2.js"> </script>
<script type="text/javascript"
src="addEntryFormAjax.js"> </script>
</head>
<body>
<form id="form">
<input type="text" id="blogText" name="blogText" size="40" />
<input type="submit" id="submit" value="submit"/>
</form>
<div id="result">
None
</div>
</body>
HTML 表单使用 JavaScript 附加提交处理程序 ( addEntryFormAjax.js
):
$(document).ready(function() {
$("#form").submit(function() {
doAjax();
// Prevent normal form submit
return false;
});
});
function doAjax() {
$("#result").html("<span>Calling ...</span>");
$.ajax({
type: "POST",
url: "addEntryAjaxPdo.php",
dataType: "html",
data: {
blogText: $("#blogText").val()
},
success: function(result) {
$("#result").html(result);
}
});
}
如果提交按钮被按下,提交处理程序使用 AJAX 调用 PHP 脚本addEntryAjaxPdo.php
将数据插入数据库:
<div>
<?php
// Sleep 3s, simulate a long running request
sleep(3);
$host = "localhost";
$db = "sandbox";
$user = "dev";
$pass = "dev";
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$stmt =
$conn->prepare(
"insert into blog (blogText, blogTimestamp) values (:blogText, now())");
$stmt->bindParam(':blogText', $_REQUEST['blogText']);
$stmt->execute();
$sql = "select last_insert_id()";
$query = $conn->query($sql);
$row = $query->fetch(PDO::FETCH_ASSOC);
echo "Inserted <em>" . $_REQUEST['blogText'] . "</em> into blog, id is "
. $row['last_insert_id()'];
?>
</div>
AJAX 调用的状态/结果显示在div
元素的 HTML 页面中。