如何在通知中添加AJAX提交表单而无需重新加载页面

How to add a AJAX submit form inside a notification without reloading the page?

本文关键字:新加载 加载 通知 添加 表单 提交 AJAX      更新时间:2023-09-26

我正在使用通知toastr js (http://codeseven.github.io/toastr/)的jQuery插件,我试图在通知气球中添加一个联系人表单,并在提交时使用AJAX。即使该表单在toastr.info('')之外工作,我也不能使其在脚本中发生。当我点击提交时,它会刷新页面。

如何解决这个问题?

Ajax脚本

$(function(){
    $("#contactform").submit(function(event){
        event.preventDefault();
        $.post('mailme.php', $("#contactform").serialize(), function(data) {
        });
    });
});

HTML表单

<form id="contactform" method="post" name="myform">
    <input name="phone" type="text"><input id="submit" name="Submit" type="submit" value="send">
</form>

toastr.info('I put the above HTML code in here')

小提琴

http://jsfiddle.net/e0k6e0vc/2

尝试在最后取消绑定submit:

$("#contactform").on('submit',function(event){
    event.preventDefault();
    $.post('mailme.php', $("#contactform").serialize(), function(data) {
    });
    $("#contactform").unbind('submit');
    return false;
});

好吧. .由于表单是动态添加的,它没有识别提交事件,因此下面的方法将完成工作:

演示

$(document).on('submit',"#contactform",function(event){
    event.preventDefault();
    $.post('mailme.php', $("#contactform").serialize(), function(data) {
    });
    $("#contactform").unbind('submit');
    return false;
});