【问题标题】:Django json, Resource interpreted as Document but transferred with MIME type application/json:Django json,资源解释为 Document,但使用 MIME 类型 application/json 传输:
【发布时间】:2017-07-10 11:25:29
【问题描述】:

我一直在尝试为 django 1.10 创建一个注册表单,它几乎可以正常工作,只是当我使帖子正常工作时,但会重定向到 ajax 帖子的 url,并且在 Chrome 检查器中我看到如下内容:资源解释为 Document,但使用 MIME 类型 application/json 传输:“http://127.0.0.1:8500/reg/”。

然后显示我的 json 响应:{"reg": "ok", "email": "logdo@fujasldm.com"}

由于这种不受欢迎的重定向,我无法处理我的表单页面上的响应。

这是我的 ajax:

$('#botonregistro').on('submit', function(e) {
 e.preventDefault();
 console.log("reg!") // sanity check

 $.ajax({
  url: "/reg/", // the endpoint
  type: "POST", // http method
  data: {
   username: $('#id_username').val(),
   password: $('#id_password').val(),
   email: $('#id_email').val(),
   sexo: $('#id_sexo').val(),
   interes: $('#id_interes').val()

  }, // data sent with the post request

  success: function(response) {
   $('.home-reg-form').empty();
   console.log(json);
   console.log("success");
  },

  error: function(response) {
   $('.home-reg-form').empty();
   $('.home-reg-form').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
  }
 });

});

这是我在帖子网址中的看法:

def reg_ajax(request):
    if request.method == 'POST':
        uname = request.POST.get('username')
        email = request.POST.get('email')
        psw = request.POST.get('password')

        user = User.objects.create_user(username=uname, email=email, password=psw)

        response = JsonResponse({'reg':'ok', 'email': email})
        return response

    else:
        response = JsonResponse({'reg':'error'})
        return response

我相信代码没问题,但也许我错过了什么。

【问题讨论】:

  • 尝试将dataType: 'json' 传递给$.ajax()。有帮助吗?
  • 感谢您的回答,已经尝试过但没有成功:(
  • 作为一个快速修复,尝试将响应的 mimetype 更改为纯文本。

标签: python json ajax django


【解决方案1】:

我未能发布我的 html 表单代码,有一个与此相关的错误,特别是在这部分:

$('#botonregistro').on('submit', function(e)

我的选择器错误,该 ID 来自我的提交按钮,而不是我的表单 ID。

感谢您的所有回答,我仍然需要从菜鸟的错误中吸取教训。

【讨论】:

  • 我也遇到了同样的问题,你能详细说说你遇到的问题吗?
  • 只需检查您是否使用了正确的选择器,问题是我的表单有像“#form”这样的 id 选择器,而且我的提交按钮有一个像“#submitbutton”这样的 id 选择器,我是使用 $('#submitbutton').on('submit', function(e) 而不是 $('#form').on('submit', function(e)
猜你喜欢
  • 2017-03-19
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2013-05-26
  • 2011-09-29
  • 2017-05-12
  • 2011-12-04
相关资源
最近更新 更多