【发布时间】:2014-11-06 14:49:36
【问题描述】:
我有一个表单,它在提交时通过对 PHP 脚本的 jQuery ajax 调用进行处理。 第一次提交表单时,jQuery 捕获事件,运行 ajax 调用和 PHP 脚本并从 PHP 脚本返回数据,并将其放入所需的 HTML 元素中。
但是,如果第二次按下提交按钮,则表单提交正常,jQuery 无法“防止默认”。所以整个页面都被重新加载了。
jQuery 代码
$(document).ready(function() {
// catch form submittion
$('#user_account_form').submit(function(ev) {
// prevent default action and propagation
ev.preventDefault();
ev.stopPropagation();
// pull data from the form attributes
var href = $(this).attr('action');
var postData = $(this).serializeArray();
// run the ajax call
var request = $.ajax({
url: "view/jquery/" + href,
type: "post",
data: postData,
dataType: "json"
});
// ajax call completed?
// -- echo returned data to elements
request.done(function(data) {
// put the refreshed form (provided by PHP script) in the #user_account element
$('#user_account').html(data.form);
// put the system message (provided by PHP script) in the #sysmsg element
$('#sysmsg').html(data.sysmsg).delay(2000).fadeOut(100);
});
// on fail, log to console
request.fail(function(jqXHR, textStatus, errorThrown) {
console.log('error processing form data: ' + textStatus + " [" + errorThrown + "]");
});
});
});
PHP 代码
this is basically a simple script that checks the entered data from the form
against the data in the database. If the entered password equals the database
password the database is updated, otherwise it will only return a system message
to the user that the password was incorrect.
我认为错误在于我的 jQuery 代码中遗漏了一些东西,这使得 jQuery 捕获了第二、第三、第四等提交。
【问题讨论】:
-
我猜这会让你感到困惑
$('#user_account').html(data.form);看起来正在创建一个新表单。 jQuery 不会自动为您重新应用您的逻辑。你需要明确地这样做。 -
"// 将刷新的表单(由 PHP 脚本提供)放在#user_account 元素中" 你的意思是,一个没有提交事件的新表单?
-
stakolee,Kevin B,说得好。从来没想过。 PHP 脚本确实构建了一个全新的表单。所以不知何故,新表单的提交动作没有被 jQuery 脚本捕获是有道理的。谢谢。
-
我认为代表可以解决您的问题