返回JSON响应,而不会重定向

问题描述 投票:1回答:2

我是新Django的,我试图更新我的视野,不会重新导向,我试图返回时,视图功能被称为JSON文件,但我似乎无法找到如何做到这一点withouth的重定向一些网址。

我想这可能是与我的urls.py:...路径(“#”,views.myFunction,名称=“myFunctionName”)。

我搞乱角落找寻与出现在djangoproject.com Django的教程

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
<a href="{% url 'polls:myfunction' %}">doFunction</a>

我的观点功能是这样的:

def myfunction(request):
    return JsonResponse({'ayy':'lmao'})

和urls.py:

from django.urls import path


from . import views

app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path(r'#', views.myfunction, name='myfunction'),
path('form', views.FormView.as_view(), name='form'),
json ajax django
2个回答
0
投票

那么,什么是最有可能发生在这里的Django的URLS是找到索引页,并重定向到该视图。该#英镑或数字符号通常表示在网页的重定向。


0
投票

首先,在你的代码中没有AJAX。 <a href="{% url 'polls:myfunction' %}">doFunction</a>会重定向到一个全新的页面。其次,你在urls.py以myfunction路径是不正确的。

下面是你可以做什么的例子。我也建议你阅读this。我使用JQuery,但随时与您喜欢什么适应。

URLs.朋友:

    #...
    path('ajax/domyfunction/', views.myfunction, name='myfunction')
]

HTML模板:

<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize}}</li
{% endfor %}
</ul>
<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
<button id="b_function">doFunction</button>
<script>
$("#b_function").click(function () {
    $.ajax({
        url: '{% url "polls:myfunction" %}',
        dataType: 'json',
        success: function (data) {
            alert(data.ayy);
        }
    });
});
</script>
© www.soinside.com 2019 - 2024. All rights reserved.