【发布时间】: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'>×</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 更改为纯文本。