【问题标题】:Create and submit a form dynamically via AJAX通过 AJAX 动态创建和提交表单
【发布时间】:2013-11-17 01:32:13
【问题描述】:

我有一个带有编辑链接的喊话框。单击时(下面的代码)会提示编辑帖子,然后在提交时动态创建表单并将表单提交到另一个页面进行处理。

最初其他页面会处理它并重定向回用户所在的页面。但是我改变了我的喊话框的显示方式。

我想要做的是动态创建表单,但不是将其提交到其他页面(实际上它在我的浏览器中将我带到操作页面,我想使用 AJAX 提交表单,以便我永远不会离开我当前所在的页面。

所以基本上我可以在主页上,编辑一个帖子,然后当我确认编辑时,我应该留在主页上,然后表单将在后台通过 AJAX 处理,并且会重新加载喊话箱容器(而不是页面本身)。

$('span.edit a').click(function (event) {
    event.preventDefault();
    var id = $(this).attr('id');
    var url = $(this).attr('href');
    var new_post = prompt('', $('#shoutbox_comment_' + id).html());

    if (new_post != '' && new_post != null && new_post != $('#shoutbox_comment_' + id).html()) {
        var form = $(
            '<form action="' + url + '" method="post">' +
            '<input type="hidden" name="comment" value="' + new_post + '">' +
            '<input type="hidden" name="id" value="' + id + '">' +
            '<input type="submit">' +
            '</form>');
        $('body').append(form);
        $(form).submit();

        $('#shoutbox_container').load('../../website/inc/views/shoutbox/shoutbox.php?p=' + $(this).parent().attr('id'));
    } else if (new_post != null) {
        alert("Your post could not be edited. Make sure that your comment is not blank and that you've made changes.");
    }
});

我已经为删除链接获得了 AJAX,但由于发布数据的表单,我无法确定如何在后台提交。

【问题讨论】:

    标签: php jquery ajax forms


    【解决方案1】:

    其实我已经明白了! >

    $('span.edit a').click(function (event) {
        event.preventDefault();
        var id = $(this).attr('id');
        var url = $(this).attr('href');
        var new_post = prompt('', $('#shoutbox_comment_' + id).html());
    
        if (new_post != '' && new_post != null && new_post != $('#shoutbox_comment_' + id).html()) {
            var form = $(
                '<form action="' + url + '" method="post">' +
                '<input type="hidden" name="comment" value="' + new_post + '">' +
                '<input type="hidden" name="id" value="' + id + '">' +
                '<input type="submit">' +
                '</form>'
            );
            $('body').append(form);
    
            $.ajax({
                type: 'post',
                url: url,
                data: form.serialize()
            });
    
            $('#shoutbox_container').load('../../website/inc/views/shoutbox/shoutbox.php?p=' + $(this).parent().attr('id'));
        } else if (new_post != null) {
            alert("Your post could not be edited. Make sure that your comment is not blank and that you've made changes.");
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2014-05-10
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-21
      相关资源
      最近更新 更多