jquery在单击div元素后使用ajax提交表单

时间:2014-12-20 11:53:27

标签: jquery ajax forms click submit

我在处理这个脚本时遇到了麻烦。我想在点击div元素后通过触发器提交将表单作为ajax发送。

这是表格代码:

<div title="add to Favorits" id="social1549" class="favtrigger nobtn transition">
    <form name="favoritform" id="formsocial1549" action="/dienstleister/fotografen/1549/verlobungsfotos-im-studio-hochzeitsfotografie" method="post" accept-charset="utf-8">
        <input type="hidden" name="favorit" value="1549">
        <div id="submitsocial1549" class="layout">
            <div class="favicon_off"></div>
            <p>as Favorit</p>
        </div>    
    </form>
</div>

这是jquery代码。

<script>
    $(document).ready(function() {
        $('.favtrigger').click(function() {
            var favid = $(this).attr('id');
            var form = $(this).find('#form' + favid);
            alert ('until here it works'); // this works
            form.submit(function(event) {
                alert ('this doesn't work'); // here nothing happens
                event.preventDefault();
                var action = form.attr('action'),
                    method = form.attr('method'),
                    data = form.serialize();
                $.ajax({
                    url: action,
                    type: method,
                    data: data,
                    success: function(data) {
                        var data = $('#' + favid + ' .layout', data);
                        $('#' + favid + ' .layout').replaceWith(data);
                    }
                });
            });
        });
    });
</script>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果您仅使用它来检索操作链接,我认为无需提交表单。我会完全取消表格提交。

$(document).ready(function() {
    $(document).on('click', '.favtrigger', function() {
        var favid = $(this).attr('id');
        var form = $(this).find('#form' + favid);
        var action = form.attr('action'),
            method = form.attr('method'),
            data = form.serialize();

        $.ajax({
            url: action,
            type: method,
            data: data,
            success: function(data) {
                var data = $('#' + favid + ' .layout', data);
                $('#' + favid + ' .layout').replaceWith(data);
            }
        });

    });
});