Django:无需重新加载即可更新页面

Esr*_*rat 3 javascript python django ajax page-refresh

我想用按钮操作更新我的homepage.html并显示来自服务器的一些结果。但问题是当我点击按钮时,整个页面都在重新加载。在这里,我的项目名称是“T2KG”。我的表单标签如下所示:

<form method="POST">
        {% csrf_token %}

        <center><textarea placeholder="Give a input sentence....."
      class="text" name="sent" rows="5" cols="70" font="15px arial, sans-serif" autofocus>Barack Obama born in Hawaii. Hawaii locates in USA.</textarea></center><br>
        <button type="submit" class="btn btn-primary btn-block" id="display_result">Generate Triple</button>
</form>
Run Code Online (Sandbox Code Playgroud)

通过在许多网站上搜索,我了解到我的 view.py 和 urls.py 不正确,而且我必须使用 AJAX。但是我不知道在这种情况下如何实施。我试过了,但找不到任何出路。在 view.py 中,我返回这样的值:

def result(request):
text = 'null'
if request.method == 'POST':
    form_input = Sentence(request.POST)
    if form_input.is_valid():
        text = form_input.cleaned_data['sent']
    else:
        form_input = Sentence()

triples = getTriples(text)

ent_list = entityList(text)
triples = predicateList(aggregate(triples, ent_list))
return render(request, './T2KG/homepage.html',{'triples': triples, 'json_triples': json.dumps(triples), 'text':text})
Run Code Online (Sandbox Code Playgroud)

我的 urls.py 是:

urlpatterns = [
path('', views.set_sent, name='set_text'),
url(r'^T2KG/homepage', views.result, name='result'),]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Run Code Online (Sandbox Code Playgroud)

请帮我。

Ama*_*ngh 6

What your looking is an ajax call to update the data on the page without the whole page refresh. For that, you would require a javascript call to send the form data to the backend and receive a json object back on success.

You can write a separate view for that or handle that by method check in the same view at python end(I prefer sep view for APIs). If using the same view remember to return the JSON object instead of a template renderer.

javascript 所做的只是从您的网页中获取表单数据并将其发送到指定的 URL,然后等待响应。为了应用更改,它需要一个响应(#can read about js promises)。所以需要有一个后端(在这种情况下是 python)来监听这个调用并返回适当的数据(成功时)。

一个不错的关注链接可以是:

https://www.geeksforgeeks.org/handling-ajax-request-in-django/

https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

http://www.tangowithdjango.com/book17/chapters/ajax.html