简体   繁体   中英

how to return data in a format json?

please help.

a form. when you send it to the next page is loaded by the controller:

from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import loader, RequestContext
from reviewsFancy.models import ReviewsFancy
from django.cong import settings
import json


def reviewsFancyCall(request):
    if request.method == "POST" and request.is_ajax():  
        c = ReviewsFancy(
            title=request.POST.get("title", ""),
            name=request.POST.get("name", ""),
            message=request.POST.get("message", ""),
        )
        c.save()

        with open(settings.BASE_DIR + 'qwe.txt', "wb") as f:
            f.write(bytes('ok', 'UTF-8'))

        data = [['result', 'ok']]
        return json.dumps(data)
    else:
        with open(settings.BASE_DIR + 'qwe.txt', "wb") as f:
            f.write(bytes('no', 'UTF-8'))

        data = [['result', 'no']]
        return json.dumps(data)

as a result everything is working as intended. the data is successfully written to the table. but I would check the returned data as follows:

..................
$.ajax({
    url: "/reviewsFancy/call/",
    type: 'POST',
    dataType: "json",
    data: {
        "title": title.val(),
        "name": name.val(),
        "message": message.val(),
    },
    error: function() {
        console.log('err');
        alert('error');
    },

    success: function(data) {
        console.log('succ');
        console.log(data['result']);
        title.val('');
        name.val('');
        message.val('');
        $('.reviews_fancy').toggleClass('hide');
        alert('success');
    },
...............

but in the console I get the error:

POST http://127.0.0.1:8000/reviewsFancy/call/ 500 (INTERNAL SERVER ERROR) jquery.2.min.js:6
XHR finished loading: "http://127.0.0.1:8000/reviewsFancy/call/". jquery.2.min.js:6
err 

Every view in Django must return a HttpResponse object, in your case:

return HttpResponse(json.dumps(data), content_type='application/json')

I would also suggest returning a dictionary rather than a list as your response:

data = {'result': 'ok'}

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