javascript - Ajax 表单提交

标签 javascript jquery ajax

我知道这个问题在这里被问过一百万次,我也看过几个例子,但我不明白为什么要提交这个表单。 Ajax 似乎没有被调用,所以我认为它很简单,比如 div id 问题。这 30 分钟我一直很沮丧。

JS:

$('#genform').submit(function (e) {
    alert('hi');
    e.preventDefault();
    $.ajax({
        url: "month.php",
        type: "post",
        data: $('#form').serialize(),
        success: function (msg) {
            $("#info").html(msg);
        }
    });
});

HTML:

<!-- trigger button -->
<div class="col-md-4">
<a href="#" id="toggle" class="btn btn-default dropdown-toggle btn-sm"> Bulk PDF Export <span class="caret"></span></a> 
</div>
<!--- popup form div -->
<div id="gendiv" style="display:none;">
    <form id="genform">
        <div class="form-input">
            <select name="month">
                <option value="2013-09-01">September 2013</option>
                <option value="2013-08-01">August 2013</option>
                <option value="2013-07-01">July 2013</option>
            </select>
        </div>
        <div class="form-input"><i class="icon-ellipsis-horizontal"></i> PGY-1  <span class="pull-right"><input type="checkbox" id="pgy1" checked name="pgy[1]"></span> 
        </div>
        <div class="form-input"><i class="icon-ellipsis-horizontal"></i> PGY-2  <span class="pull-right"><input type="checkbox" id="pgy2" checked name="pgy[2]"></span> 
        </div>
        <div class="form-input"><i class="icon-ellipsis-horizontal"></i> PGY-3  <span class="pull-right"><input type="checkbox" id="pgy3" checked name="pgy[3]"></span> 
        </div>
        <div class="form-input" style="text-align:center">
            <button type="submit" class="btn btn-primary btn-xs">Generate</button>
        </div>
        <div id="info"></div>
    </form>
</div>

fiddle :http://jsfiddle.net/KQ2nM/2/

最佳答案

它不起作用的原因是 popover 克隆了表单,然后将 html 放在类 .popover-content 的 div 中。

这意味着您绑定(bind)的事件仅附加到隐藏的#gendiv 内的原始 #genform

改用这个:

$(document).on('submit', '#genform', function(e) {
    e.preventDefault();
    $.ajax({
        url: "month.php",
        type: "post",
        data: $(this).serialize(),
        success: function (msg) {
            $("#info").html(msg);
        }
    });
});

这使用了 jQuery 的 .on()函数并将事件处理程序附加到 document,它主要监视在 ID 为 #genform 的表单上触发的 submit 事件。通过将事件处理程序附加到 document 而不是直接附加到目标元素,它会被 submit 事件触发,而不管 id 是否为 #genform< 的表单 在绑定(bind)事件时存在。

它在这里工作:http://jsfiddle.net/KQ2nM/4/

关于javascript - Ajax 表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18576365/

相关文章:

javascript - 当内容达到一定大小时出现空白页

jQuery AJAX Post 不发布数据

javascript - 在 React Native 中根据命名约定导入 typescript 文件

javascript - vuejs 如果/否则 : check if element exsists else add a element

javascript - 一次更新设置多个 Ramda 镜头

JavaScript/jQuery : Why is my increment not working?

javascript - 为什么这个简单的 JavaScript 函数没有像我预期的那样工作?尝试确定复选框是否被选中

javascript - 某些字段 id 的 Ajax POST 数据

php - 单击编辑按钮在 Bootstrap 模式中显示特定行数据

javascript - 在 Grunt 中同时使用 Compass 和 Autoprefixer