简体   繁体   English

无法使用jQuery序列化表单(Django)

[英]Can't serialize form with jQuery (Django)

I have a template 我有一个模板

  <form method="POST" action="{% url 'ajax_question' %}" role="form" id="question-form">
    {% csrf_token %}
    {% for answer in answers %}
      <div class="radio"><label name="answers-radio">
        <input type="radio" name="answers-radio"
               value ="{{ answer.id }}">{{ answer.text }}
      </label></div>
    {% endfor %}
  </form>

(actually, it is part of template, but the rest is a things like block , extends , etc) (实际上,它是模板的一部分,但其余部分是诸如blockextends类的东西)

I try to serialize this form to send with AJAX request, but this code 我尝试序列化此表单以与AJAX请求一起发送,但是此代码

$("#question-form").serialize()

don't work properly, it only returns 工作不正常,只会返回

csrfmiddlewaretoken=yYa3KW1pFWCAquX3FUsbMOHTfXE2z8g3 csrfmiddlewaretoken = yYa3KW1pFWCAquX3FUsbMOHTfXE2z8g3

Form renders correct, i see all radio elements and other elements. 表单呈现正确,我看到所有无线电元素和其他元素。

Perhaps you could use 也许你可以用

$("#question-form").serializeArray();

Here is a solution you could use or look at for ideas. 这是您可以使用或寻找想法的解决方案。 Hope this helps! 希望这可以帮助!

https://jsfiddle.net/gabrieleromanato/bynaK/ https://jsfiddle.net/gabrieleromanato/bynaK/

If you serialize the form on page load, you're only serializing the initial data (which is why you're only getting the csrf_token value). 如果在页面加载时序列化表单,则仅序列化初始数据 (这就是为什么仅获得csrf_token值的原因)。 Instead, you want to serialize all of the fields, which won't have values until the fields have been filled out by the user, and submit is fired. 相反,您要序列化所有字段,直到用户填写了这些字段并触发了submit ,这些字段才具有值。

You'll have to adjust your form slightly to not POST immediately (you could remove the action Url if you're planning to use ajax and put that url in your ajax method). 您必须稍微调整一下窗体,使其不立即发布(如果您打算使用ajax,则可以删除操作Url,并将该网址放入ajax方法中)。 But something like this should work for you: 但是这样的事情应该对您有用:

$(document).ready(function() {
    $('#question-form').on('submit', function(event){
        event.preventDefault();
        var form_data = $('#question-form').serialize();
    });
})

愚蠢的错误:我没有选择任何无线电元素,所以什么也没发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM