gpt4 book ai didi

python - 如何以json格式返回数据?

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:35 26 4
gpt4 key购买 nike

请帮忙。

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

关于python - 如何以json格式返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22859206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com