开发者

jQuery parsererror on simple JSON returned from Django

开发者 https://www.devze.com 2023-04-05 23:09 出处:网络
I\'m doing a pretty simple thing here, making a POST request to Django from jQuery, and I\'m getting a strange error for a pretty simple scenario. I have the following view function:

I'm doing a pretty simple thing here, making a POST request to Django from jQuery, and I'm getting a strange error for a pretty simple scenario. I have the following view function:

from django.views.generic.simple import direct_to_template as dto

def do_login(request):
    if request.method == "POST":
        return dto(request, "path/to/template.json", {
            'success': False,
            'cause': None
        }, mimetype="text/json")

Here's my tem开发者_StackOverflow社区plate:

{ success : {{success|lower}}{% if cause %}, cause : {{cause}}{% endif %} }

...and here's my jQuery:

$.ajax("/login/", { type: "POST",
    data: $("#loginForm").serialize(),
    success: function(data) {
        console.log("login response: " + data);
    },
    error: function(data, stats, error) {
        console.log("login fault: " + data + ", " + 
                stats + ", " + error);
    }
});

Pretty simple, right? Here's what I get in the console:

login fault: [object Object], parsererror, SyntaxError: Unexpected token s

What's going wrong here? If I don't set the mimetype on my render method, then everything works fine. The problem is, I'd like to return JSON without having to force jQuery to reparse it. Can anyone spot my mistake here? I can't seem to see it.


The JSON is not valid. You need quotation marks around the identifiers, so "success" instead of success and "cause" instead of cause.


from django.utils import simplejson as json

def do_login(request):
    if request.method == "POST":
        return HttpResponse(json.dumps({'success': False, 'cause': None}), content_type='application/json')
0

精彩评论

暂无评论...
验证码 换一张
取 消