Ajax返回整页

时间:2018-11-03 16:15:47

标签: javascript python jquery ajax django

Ajax返回整页而不是返回Input的Value。带有Django的Ajax不能正常运行。它必须是一页的Web应用程序。我试图将Calc的模板制作为单独的页面,但也无法正常工作。

Urls.py

urlpatterns = [
    url(r'', views.main, name = 'main'),
    url(r'calc/$', views.calc, name = 'calc')
]

Views.py

def main(request):
    return render(request, 'main/index.html',
context = {
    'some': some
    }
)

def calc(request):
    if request.GET:
        outputdata = request.GET('somedata')
        return HttpResponse(outputdata)

index.html

...
<div>
    <form action="{% url 'calc' %}" method="GET">
        {% csrf_token %}
        <input type="text" id="someinput" value="somevalue">
    </form>
    <button type="submit" id="somebutton">Button</button>
</div>
...

script.js

$(document).ready(function() {
    $('#somebutton').on('click', function(event) {
        $.ajax({
            type: 'GET',
            url: 'calc',
            data: {
                'somedata': $('#someinput').val()
            },
            success: function(data) {
                alert(data);
            }
        });
    });
});

警告

感谢所有答复。

解决方案是使用路径而不是url。

path('', views.main, name = 'main'),
path('calc/', views.calc, name = 'calc')

然后编写outputdata = request.GET.get('somedata')而不是outputdata = request.GET('somedata')。

2 个答案:

答案 0 :(得分:1)

问题可能是您的主要URL模式匹配所有内容。因此,当您发出Ajax请求时,该请求由返回整页的视图而不是返回单个值的视图提供。

确保使用开始和结束锚点:

url(r'^$', views.main, name = 'main'),
url(r'^calc/$', views.calc, name = 'calc')

或使用新的路径语法:

path('', views.main, name = 'main'),
path('calc/', views.calc, name = 'calc')

答案 1 :(得分:0)

您使用return

  \Auth::logout();
    $request->session()->invalidate();

但是您需要使用

HttpResponse(outputdata) 

因此导入JsonResponse并将HttpResponse更改为JsonResponse

from django.http import JsonResponse 

return JsonResponse({"foo":"bar")
相关问题