我按照教程来调整代码。在这里,我尝试在提供“ID”值时使用 AJAX 自动填充表单字段。我是 Jquery 的新手,无法使用此代码。
编辑 1:在测试代码时,Jquery 不会阻止表单提交和发送 AJAX 请求。
HTML 表单
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
我尝试更改 Jquery 代码,但仍然无法正常工作。我认为 Jquery 在这里制造了一个问题。但我找不到错误或错误代码。如果您让我朝着正确的方向前进,那将非常有帮助。
编辑2:我尝试使用
return false;
代替
event.preventDefault();
以防止表单提交,但它仍然无法正常工作。知道我在这里做错了什么吗?
jQuery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}