首页 > 解决方案 > 如何在另一个 django 视图中使用 POST 获取的数据 ERROR 200

问题描述

我想使用通过 AjaxQuery 获取的数据,解析该数据并将用户发送到另一个视图以执行其他操作。但是,我收到错误 200 和我的测试视图片段,我不知道为什么!我想要做的主要思想是使用 js 函数获取用户位置,然后使用 AjaxQuery 获取坐标,在其功能是处理数据的视图中使用 POST,然后将用户发送到另一个视图我可以使用这些协调员做其他事情。

Ajax 查询

$(document).ready(function(sol) {
    $("#send-my-url-to-django-button").click(function(sol) {
        $.ajax({
            url: "/establishments/process_url_from_client/",
            type: "POST",
            dataType: "json",
            data: {
                lat: sol[0],
                lon: sol[1],
                csrfmiddlewaretoken: '{{ csrf_token }}'
                },
            success : function(json) {
                alert("Successfully sent the URL to Django");

            },
            error : function(xhr,errmsg,err) {
                alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
            }
        });
    });
});

视图.py

def get_coordinates_view(request):
return render(request, 'base2.html')

def process_url_from_client(request):
res = request.POST.get('data')
return render(request, "results.html")

网址.py

urlpatterns = [
path("", views.get_coordinates_view),
path("process_url_from_client/", views.process_url_from_client),]

现在的 results.html 只是一个带有 hello 的 html,我得到的错误是:无法将 URL 发送到 django。错误 200:您好!

非常感谢!

标签: djangoajaxdjango-modelsdjango-rest-frameworkdjango-views

解决方案


您的错误信息误导了您。向 Django 发送请求没有错误。但是,在理解响应时存在错误

dataType: "json"通过在$.ajax调用中指定,您已经告诉 jQuery 期待 JSON 响应。但是您的 Django 视图没有返回 JSON,它(出于某种原因)呈现 HTML 模板。正如这个答案所示,当 jQuery 无法根据 dataType 解析响应时,它会触发错误处理程序

要么放弃dataType,要么最好实际返回 JSON:

return JsonResponse({'message': 'ok'})

推荐阅读