表单第一次通过jQuery提交,第二次通过PHP提交


Form submits 1st via jQuery, 2nd via PHP

我有一个表单,提交时通过对PHP脚本的jQuery ajax调用进行处理。表单第一次提交时,jQuery捕获事件,运行ajax调用和PHP脚本,并从PHP脚本返回数据,将其放入所需的HTML元素中。

但是,如果第二次按下提交按钮,表单将正常提交,可以说jQuery无法"preventDefault"。所以整个页面都被重新加载了。

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_form').on('submit', function(ev) {});

代替:

$('#user_account_form').submit(function(ev) {});

这是因为据我所知,提交按钮位于从后端刷新的数据中,这意味着该按钮没有绑定到任何事件,因为它是一个全新的按钮。上的jQuery将事件绑定到该元素的所有实例,即使它们是在将来创建的。

重要提示:如果您使用jQuery<1.7,而不是on(),请使用live()。

也许可以尝试使用计数器,这样你就可以知道你点击提交btn 的次数

$(document).ready(function() {
var counter = 0;
// catch form submittion
    $('#user_account_form').submit(function(ev) {
        // If first click
        if(counter === 0){
            // Do the preventDefault and ajax thing
        }
        else{
            // Do nothing or what you expect for a >2nd click
        }
        // Increment counter
        counter++;
    })
});

在阅读了您关于PHP脚本构建一个全新表单的帖子后,我想"如果我只需要刷新1或2个字段,为什么要构建一个完整的新表单?"。因此,我更改了PHP脚本,只返回更改字段的数据库中的数据,并将其以json格式发送到我的jQuery脚本。然后调整我的jQuery脚本以读取json对象,并将新值放入相应的字段中。现在它按预期工作。

更改jQuery代码

....
request.done(function(data) {
    $('#email').val(data.email);
    $('#sysmsg').html(data.sysmsg).delay(2000).fadeOut(100);
});

更改了PHP代码

....
$email = $main->getUserDetails('email');
$array = array("sysmsg" => $msg, "email" => $email);
$data = json_encode($array);
echo $data;

感谢您的投入,它帮助我弄清楚了要更改什么来改进我的代码。