简体   繁体   English

Django 视图在 AJAX POST 请求后不重定向

[英]Django view not redirecting after AJAX POST request

I've switched from sending data from a <form> to building a JSON string myself and sending that to the server.我已经从从<form>发送数据切换到自己构建 JSON 字符串并将其发送到服务器。

I was expecting that after sending a POST request to my view that the browser would render the JSON response -- basically, show me a page of the posted JSON data.我期待在向我的视图发送POST请求后,浏览器会呈现 JSON 响应——基本上,向我展示已发布 JSON 数据的页面。 That was the case when I submitting via a form POST request.当我通过表单 POST 请求提交时就是这种情况。

What actually happens is that the browser doesn't do anything.实际发生的是浏览器什么都不做。 But I can nevertheless see that the server is sending the right response to the browser.但是我仍然可以看到服务器正在向浏览器发送正确的响应。 But why doesn't the page redirect to show the JSON data?但是为什么页面不重定向以显示 JSON 数据?

javascript.js

async function submit() {

  let response = await fetch('/cartography/', {
    method: 'POST',
    body: JSON.stringify({test: "test"}),
    headers: {
      "Content-Type": "application/json;charset=utf-8",
      "X-CSRFToken" : csrfToken.value,
    },
  })
}

views.py

def cartography_view(request):
    if request.method == 'POST':
        request_data = json.loads(request.body)
        json_data = json_dumps(request_data)
        return JsonResponse(json_data) # <-- doesn't redirect. but why?

urls.py

path('cartography/', cartography_view, name = 'cartography'),

home.html

<button class="pushable" onclick="submit"/>submit to cartography</button>

Edit: this is the response:编辑:这是回应:

Response { type: "basic", url: "http://127.0.0.1:8000/cartography/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }

Your returning json from your view, I would receive it in your Javascript at success and print to console to make sure it's coming back.您从您的视图中返回的 json,我会在成功时在您的 Javascript 中接收它并打印到控制台以确保它返回。

Essentially you still need to do something with the request.本质上,您仍然需要对请求做一些事情。 I normally do this with an Ajax request and on success, receive the return data and display it, show it in alert or pop-up or refresh the page.我通常使用 Ajax 请求执行此操作,并在成功时接收返回数据并显示它,在警报或弹出窗口中显示它或刷新页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM