首页 > 解决方案 > 使用ajax POST将json数据从浏览器发送到Django视图后没有响应

问题描述

我正在使用 handsontable 在我的 Web 应用程序上模拟电子表格。我想将用户输入电子表格的 json 数据发送到我的数据库。

html按钮:

<button id="send_post" class="btn size-medium bg-green text-white shadow hover-moveup">Send Post Request</button>

JS:

document.getElementById("send_post").addEventListener("click", function(event) {
    $.ajax({
      url: 'http://127.0.0.1:8000/',
      headers: { "X-CSRFToken": csrf_token },
      type: "POST",
      dataType: "json",
      data: JSON.stringify(hot.getSourceData()),
      statusCode: {
        200: function (your_Response_Data) {
            console.log(JSON.stringify(hot.getSourceData()))
        },
        // ... handle errors if required
        404: function () {
        }
      },
      complete: function (jqXHR, textStatus) {
      }
    });


  })

视图.py

@login_required(login_url='/login/')
def index(request):
    user_id = request.user
    if request.is_ajax():

        if request.method == "POST":
            received_json_data = json.loads(request.body)

            return HttpResponse(received_json_data, content_type="application/json")

终端:

[04/Apr/2019 01:19:23] "POST / HTTP/1.1" 302 0

我在视图中收到数据,但 Httpresponse 没有将数据返回给浏览器。

标签: jsonajaxdjangopost

解决方案


通过在成功的 POST 请求时设置 location.href 来解决它

statusCode: {
        200: function (your_Response_Data) {
            console.log(JSON.stringify(hot.getSourceData()));
            location.href = "/";
        },

推荐阅读