在不离开页面的情况下提交表单


Submit a Form without Leaving Page

我正在做一个调查,该调查将在FAQ页面的底部进行。我的问题是每次提交表单时,它都会将您发送到不同的页面。我想知道 - 有没有办法提交表单并有一条小消息来代替"感谢您的反馈"的调查,而不是将用户发送到另一个页面或刷新页面?

到目前为止,我有一个包含HTML表单,CSS和jQuery的文件,另一个文件包含PHP连接到数据库以及将数据插入数据库。

我希望有一个愚蠢的解释,一个例子会有所帮助,因为我对编程相对较新。

重要说明:我的jQuery设置为在用户回答非常有帮助/非常有帮助时自动提交。如果没有,下面会显示另外两个问题,底部有一个提交按钮。

更具体地说,它看起来像这样:

$(document).ready(function() {
    $('.rating').click(function() {
    $('.rating').removeClass('selected');
    ratingClick(this);
});
});
function ratingClick(that) {
console.log(that.id);
    if (that.id == 'rating4' || that.id == 'rating5') {
        //$('#questions').fadeOut('slow');
        //$('#thankYou').fadeIn('slow');
        $('#questions').submit();
    } else {
        $('#getMore').fadeIn();
        $(that).toggleClass('selected');
    }
}
$(document).ready(function() {
$('#submit').click(function(){
    //$('#questions').fadeOut('slow');
    //$('#thankYou').fadeIn('slow');
});
});

你想要的是jquery post函数:http://api.jquery.com/jQuery.post/

确保数据是 JSON。

$("#formdiv").click(function(){
     $.post("somepage",{ yourformdata} ); 
     $("#formdiv").replacewith("Thanks for filling out the form!");
}); 

您可以使用 replaceWith 函数将所需内容替换为感谢消息。

Alex,

从您提供的代码来看,离开页面的原因是由于您没有阻止单击事件上的 Default()。您的页面将在提交后始终重新加载,除非您执行中止操作。不能保证,但请尝试快速重构以:

$(document).ready(function() {
    $('#submit').click(function(e){
        e.preventDefault();
        //$('#questions').fadeOut('slow');
        //$('#thankYou').fadeIn('slow');
    });
});

这应该会让你更接近一个阶段。然后,您只需定义 ajax 逻辑,通过快速搜索可以满足您的需求。