gpt4 book ai didi

javascript - 使用 AJAX 和 Jquery 从 MySQL 填充表单字段

转载 作者:行者123 更新时间:2023-11-29 23:45:53 25 4
gpt4 key购买 nike

我按照教程来调整代码。在这里,我尝试在提供“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;
}
}

最佳答案

我不知道你在哪里将 json 响应解析为 javascript 对象(哈希)。这个jQuery method应该有帮助。看起来您也没有使用 jquery 发布表单,而是尝试发出 get 请求。要使用 jquery 正确提交表单,请使用如下内容:

$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );

此外,您是否尝试过向表单元素添加 id 属性?

<input type="text" id="name" name="name"/>

以后联系他们会更容易

var element = $('#'+element_id);

如果这不是解决方案,您可以发布从您的请求返回的 json 吗?

关于javascript - 使用 AJAX 和 Jquery 从 MySQL 填充表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25956603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com