在Django中的JS逻辑之后提交表单

时间:2015-01-06 00:44:27

标签: javascript jquery python django forms

我有一个支持用户输入的表单。提交后,一些javascript将执行一些逻辑传递给/test/ URL。目前问题是我没有被重定向到/test/网址。

JS:

$(document).ready(function() {
    var testRun = document.getElementById("test-form");
    testRun.addEventListener('submit', function(event) {
        testData["timestamp"] = new Date().getTime();
        event.preventDefault();
        // more logic
        return jsonData;
    });
});

home_page.html

  <form id="test-form" action="/test/" method="post"> {# pass data to /test/ URL #}
    {% csrf_token %}
    <div class="test-button-set">
      <button type="button" id="hdfs-test" class="btn btn-default btn-lg selected">HDFS</button>
      <button type="button" id="hive-test" class="btn btn-default btn-lg">HIVE</button>
      <button type="button" id="hdfs-hive-test" class="btn btn-default btn-lg">BOTH</button>
    </div>

    {{ form.event_textarea }}
    <button id="submit-test" type="submit" class="btn btn-default btn-lg">Submit</button>
  </form>

forms.py

class TestForm(forms.Form):
    event_textarea = forms.CharField(widget=forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event-textarea'}))

views.py

from django.shortcuts import render
from forms import TestForm
from django.http import HttpResponseRedirect


def home(request):
    if request == 'POST':
        # create a form instance and populate it with data from the request
        form = TestForm(request.POST)
        if form.is_valid():
            # process the data in form.cleaned_data as required
            form.cleaned_data()
            # redirect to a new URL:
            return HttpResponseRedirect('/test/')
    # if a GET (or any other method) we'll create a blank form
    else:
        form = TestForm()
    return render(request, 'home/home_page.html', {'form': form})

def test(request):
    return render(request, 'home/test.html', {'post': request.POST})

我的/test/网址用于显示帖子请求,因此我可以确定我发布了什么。目前JS逻辑(我已经设置了输出的指标)正在运行,但我没有被重定向,因此我不确定是否有任何内容被发布到URL

1 个答案:

答案 0 :(得分:2)

此行将阻止发生默认事件(表单提交):

event.preventDefault();

删除它,表单应按预期提交。