- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我按照教程来调整代码。在这里,我尝试在提供“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/
我尝试通过正则表达式将文本中的单引号更改为双引号。 (单字)示例:我走了。 You gona fly to planet 'Ziqtos' => 我需要在 I'm 中保留单引号,并在 You gona
我正在构建一个 API,其中大部分将包含 JSON 和 HTML 内容。但是一些非常具体的端点只呈现 true 或 false,并且还在 POST 中接受 true 或 false。这是请求或响应的整
我是一名优秀的程序员,十分优秀!