Skip to main content
 首页 » 编程设计

python之如何以json格式返回数据

2025年05月04日6artech

请帮忙。

表格。当您将其发送到下一页时, 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) 

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

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

请您参考如下方法:

Django 中的每个 View 都必须返回一个 HttpResponse 对象,在您的例子中:

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

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

data = {'result': 'ok'}