django - 如何在另一个 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:您好!
非常感谢!
解决方案
您的错误信息误导了您。向 Django 发送请求没有错误。但是,在理解响应时存在错误。
dataType: "json"
通过在$.ajax
调用中指定,您已经告诉 jQuery 期待 JSON 响应。但是您的 Django 视图没有返回 JSON,它(出于某种原因)呈现 HTML 模板。正如这个答案所示,当 jQuery 无法根据 dataType 解析响应时,它会触发错误处理程序
要么放弃dataType
,要么最好实际返回 JSON:
return JsonResponse({'message': 'ok'})
推荐阅读
- vba - 如何删除动态数据验证错误
- javascript - 关于代码中的函数,我不知道它们的含义
- producer-consumer - 如何优化并行合并元素
- xml - akka http中的文件解析和持久化
- android - 进程“命令 'C:\Users\sneha\AppData\Local\Android\Sdk\build-tools\29.0.0\aidl.exe'' 以非零退出值 -1073741819 结束
- internet-explorer - IE - C#,如何将 JavaScript 文件注入网页?
- php - 如何从数组中检索元素 - PHP
- .net - 我可以将流读入包含 Unicode BOM 的字符串吗?
- php - 如何从我的数据库中获取一个值并在输入字段中使用和显示它?
- android - 如何从事件处理程序中获取调用者作为 Kotlin 中的对象