如何以json格式返回数据?

时间:2014-04-04 09:45:13

标签: python ajax json django

请帮忙。

表格。当你把它发送到下一页时,由控制器加载:

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)

因此一切都按预期工作。数据已成功写入表中。但我会按如下方式检查返回的数据:

..................
$.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');
    },
...............

但在控制台中我收到错误:

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 

1 个答案:

答案 0 :(得分:1)

Django中的每个视图都必须返回一个HttpResponse对象,在您的情况下:

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

我还建议您回复字典而不是列表作为回复:

data = {'result': 'ok'}