jQuery和Multiple Forms,只有第一个有效

时间:2014-03-06 13:49:23

标签: javascript jquery html

我有一个包含多个元素的页面,并在单击其中一个表单时发送一些jQuery代码。

形式:

<form method="post" action="">
{% csrf_token %}
<input id="vote" name="vote" type="hidden" value="up">
<input id="post_id" name="post_id" type="hidden" value="{{submission.id}}"/>
<input type="submit" class="arrowup" value=""/>
</form>

jQuery javascript:

$(document).ready(function() {
        $("form").submit(function(e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "/button_form/",
                dataType: "json",
                data : {
                    post_id : encodeURIComponent(document.getElementById('post_id').value),
                    vote : encodeURIComponent(document.getElementById('vote').value),
                    csrfmiddlewaretoken: '{{ csrf_token }}'
                    },
                success : function(json) {
                        $('#result').html( 'post id: ' + json.post_id + ' voted: ' + json.up_or_down);
                    },
                error: function(xhr,errmsg,err) {
                        alert(xhr.status + ": " + xhr.responseText);
                }
            });
            return false;
        });
    });

第一个按钮按预期工作并获取服务器的json响应,但是所有其他按钮都不起作用。

我认为这可能是因为有多个投票和post_id表单输入,但无法找出替代策略,或者这是否真的是问题。

非常感谢任何帮助。 感谢

1 个答案:

答案 0 :(得分:0)

我认为您可以遍历所有表单并在提交事件中单独提交每个表单:

$("#formID").submit(function(e) {
    e.preventDefault();
    var url = $(this).attr('action');
    $.ajax({
    type: 'POST',
    url: url,
    dataType: 'json',    
    // All other ajax code for submitting form data
    });
});