结合使用Ajax和Django来调用后端并显示结果

时间:2018-08-21 09:33:20

标签: javascript python ajax django

我正在接受用户输入,并将其发送到Django后端进行一些文本处理。执行后端操作后,我想显示结果。

我尝试过,但是由于我是ajax的新手,所以不确定在哪里出错。任何人都可以给我正确的方法来使用ajax进行此操作吗?如果您可以提供任何参考文件的链接,我将不胜感激。

当前问题-当我单击submut按钮时,它将删除输入文本区域。

enter image description here enter image description here

我的html report.html-

{% extends 'base.html' %}
{% block content %}
  <h1>StopWordsRemoval</h1>

<script type='text/javascript'>
$(document).ready(function(){
    $(form).on('submit', function(event){
        $.ajax({
            url: 'stopwordsremoval/(?P<document1>.+)'
            type: 'POST',
            data: this.serialize(),
        }); 
    });
});
</script>

<div>
<form  method = "post" >
    {% csrf_token %}
    {{ form}}

    <button type="submit">stopwordsremoval</button>
    </div>
    </form>
    <div >
        <ul>
            <li>{{ naturallanguageprocessing }}</li> 
        </ul>
    <a href="{% url 'stopwordsremoval' %}" </a>
<style>
    div {
        width: 1000px;
        border: 5px solid green;
        padding: 10px;
        margin: 10px;
    }
</style>
</div>
  </div>

  {% endblock %}

urls.py

from django.conf.urls import url    
from . import views
urlpatterns = [
    url(r'stopwordsremoval/$', views.stopwordsremoval.as_view(), name='stopwordsremoval'),
    url(r'stopwordsremoval/(?P<document1>.+)/$',
        views.ReportDetails.as_view(), name='report_details'),
]

forms.py

from django import forms

class ReportForm(forms.Form):
    #pdb.set_trace()
    text = forms.CharField(widget=forms.Textarea(attrs={'rows': 5, 'cols': 100}))

1 个答案:

答案 0 :(得分:0)

<script type='text/javascript'>
$(document).ready(function(){
    $(button).on('click', function(event){
        var form = $(form).serialize()
        $.ajax({
            url: 'stopwordsremoval/(?P<document1>.+)' // this will not work
            type: 'POST',
            data: form,
        }); 
    });
});
</script>