简体   繁体   中英

Django- jQuery AJAX POST response- trouble parsing JSON

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:

#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:

//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.

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]

In Chrome's console I get the error:

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

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:

I keep getting "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM