Django-jQuery AJAX POST响应 - 解析JSON时遇到问题

时间:2022-10-08 21:20:27

I'm using an app that allows me to post forms responses, from an html template, asynchronously. I've verified that my POST works fine, but I'm having trouble with the response. This is the main code for the corresponding Django view:

我正在使用一个应用程序,允许我以异步方式从html模板发布表单响应。我已经验证我的POST工作正常,但是我的响应有问题。这是相应Django视图的主要代码:

#views.py from the app........

def post(self, request, *args, **kwargs):
    published = Form.objects.published(for_user=request.user)
    form = get_object_or_404(published, slug=kwargs["slug"])
    form_for_form = FormForForm(form, RequestContext(request),
                                request.POST or None,
                                request.FILES or None)
    if not form_for_form.is_valid():
        form_invalid.send(sender=request, form=form_for_form)
    else:
        # Attachments read must occur before model save,
        # or seek() will fail on large uploads.
        attachments = []
        for f in form_for_form.files.values():
            f.seek(0)
            attachments.append((f.name, f.read()))
        entry = form_for_form.save()
        form_valid.send(sender=request, form=form_for_form, entry=entry)
        self.send_emails(request, form_for_form, form, entry, attachments)
        if not self.request.is_ajax():
            return redirect(form.redirect_url or
                reverse("form_sent", kwargs={"slug": form.slug}))
    context = {"form": form, "form_for_form": form_for_form}
    return self.render_to_response(context)

def render_to_response(self, context, **kwargs):
    if self.request.method == "POST" and self.request.is_ajax():
        json_context = json.dumps({
            "errors": context["form_for_form"].errors,
            "form": context["form_for_form"].as_p(),
            "messag": context["form"].response,
        })
        if context["form_for_form"].errors:
            return HttpResponseBadRequest(json_context,
                content_type="application/json")
        return HttpResponse(json_context, content_type="application/json")
    return super(FormDetail, self).render_to_response(context, **kwargs)

and this is the javascript part of my html template responsible for the post:

这是我负责帖子的html模板的javascript部分:

//My html template.....

<script type="text/javascript">
var frm = $('#theform');
frm.submit(function () {
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        headers: {'X-CSRFToken': '{{ csrf_token }}'},
        data: frm.serialize(),
        dataType: 'json',
        success: function (data) {
            alert('TESTING...');
            var json = $.parseJSON(data);
            alert(json);
        },
        error: function(data) {
            $("#responsediv").html("Something went wrong!");
        }
    });
    return false;
});

So I can POST fine (I verified my submissions being correctly stored in the server side) but my problem lies in the success: function (data) part, as I'm having trouble parsing the json response. I've looked at many other questions about this and followed the tips people got, but I can't seem to be able to parse the json response. In this case, I get the alert for alert('TESTING...');, but var json = $.parseJSON(data); does not work, and the following alert does not happen.

所以我可以POST好(我验证我的提交正确存储在服务器端)但我的问题在于成功:函数(数据)部分,因为我在解析json响应时遇到问题。我已经看了很多关于这个问题的其他问题,并按照人们的提示,但我似乎无法解析json的反应。在这种情况下,我得到警报警报('TESTING ...');但是var json = $ .parseJSON(data);不起作用,并且不会发生以下警报。

I do not understand what the problem is. How to solve this issue?

我不明白问题是什么。如何解决这个问题?

I've confirmed that I'm in fact getting the json success response from the server, because if I try to print "data", I'll get [object Object]

我已经确认我实际上是从服务器获取json成功响应,因为如果我尝试打印“数据”,我会得到[object Object]

In Chrome's console I get the error:

在Chrome的控制台中,我收到错误消息:

Uncaught SyntaxError: Unexpected token o in JSON at position 1 at Function.parse [as parseJSON] ()

未捕获的SyntaxError:Function.parse中位置1的JSON中的意外标记o [as parseJSON]()

1 个解决方案

#1


0  

I've found my mistake. By putting in dataType: 'json', the json is already parsed, so I was effectively trying to parse it again when it was totally unnecessary. The 'solution' is here:

我发现了自己的错误。通过输入dataType:'json',json已经被解析了,所以当它完全没必要时我有效地尝试再次解析它。 '解决方案'在这里:

I keep getting "Uncaught SyntaxError: Unexpected token o"

我一直得到“Uncaught SyntaxError:Unexpected token o”

I did not remember to look for the specific error I got before posting the question, I'm sorry. I just looked for generic questions about the Django AJAX POST returns. Mods please delete this/mark as duplicate or something. I do appreciate the comments above.

我不记得在发布问题之前查找我得到的具体错误,对不起。我只是寻找关于Django AJAX POST返回的一般性问题。 Mods请删除此/标记为重复或其他内容。我非常感谢上面的评论。

#1


0  

I've found my mistake. By putting in dataType: 'json', the json is already parsed, so I was effectively trying to parse it again when it was totally unnecessary. The 'solution' is here:

我发现了自己的错误。通过输入dataType:'json',json已经被解析了,所以当它完全没必要时我有效地尝试再次解析它。 '解决方案'在这里:

I keep getting "Uncaught SyntaxError: Unexpected token o"

我一直得到“Uncaught SyntaxError:Unexpected token o”

I did not remember to look for the specific error I got before posting the question, I'm sorry. I just looked for generic questions about the Django AJAX POST returns. Mods please delete this/mark as duplicate or something. I do appreciate the comments above.

我不记得在发布问题之前查找我得到的具体错误,对不起。我只是寻找关于Django AJAX POST返回的一般性问题。 Mods请删除此/标记为重复或其他内容。我非常感谢上面的评论。