使用 Django 和 Python 创建 JSON 响应 [英] Creating a JSON response using Django and Python

查看:23
本文介绍了使用 Django 和 Python 创建 JSON 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将服务器端 Ajax 响应脚本转换为 Django HttpResponse,但显然它不起作用.

I'm trying to convert a server side Ajax response script into a Django HttpResponse, but apparently it's not working.

这是服务器端脚本:

/* RECEIVE VALUE */
$validateValue=$_POST['validateValue'];
$validateId=$_POST['validateId'];
$validateError=$_POST['validateError'];

/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$arrayToJs[1] = $validateError;

if($validateValue =="Testuser"){  // Validate??
    $arrayToJs[2] = "true";       // RETURN TRUE
    echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';  // RETURN ARRAY WITH success
}
else{
    for($x=0;$x<1000000;$x++){
        if($x == 990000){
            $arrayToJs[2] = "false";
            echo '{"jsonValidateReturn":'.json_encode($arrayToJs).'}';   // RETURNS ARRAY WITH ERROR.
        }
    }
}

这是转换后的代码

def validate_user(request):
    if request.method == 'POST':
        vld_value = request.POST.get('validateValue')
        vld_id = request.POST.get('validateId')
        vld_error = request.POST.get('validateError')

        array_to_js = [vld_id, vld_error, False]

        if vld_value == "TestUser":
            array_to_js[2] = True
            x = simplejson.dumps(array_to_js)
            return HttpResponse(x)
        else:
            array_to_js[2] = False
            x = simplejson.dumps(array_to_js)
            error = 'Error'
            return render_to_response('index.html',{'error':error},context_instance=RequestContext(request))
    return render_to_response('index.html',context_instance=RequestContext(request))

我使用 simplejson 对 Python 列表进行编码(因此它将返回一个 JSON 数组).我还没有弄清楚问题所在.但我认为我在回声"方面做错了.

I'm using simplejson to encode the Python list (so it will return a JSON array). I couldn't figure out the problem yet. But I think that I did something wrong about the 'echo'.

推荐答案

我通常使用字典而不是列表来返回 JSON 内容.

I usually use a dictionary, not a list to return JSON content.

import json

from django.http import HttpResponse

response_data = {}
response_data['result'] = 'error'
response_data['message'] = 'Some error message'

在 Django 1.7 之前,你会像这样返回它:

Pre-Django 1.7 you'd return it like this:

return HttpResponse(json.dumps(response_data), content_type="application/json")

对于 Django 1.7+,使用 JsonResponsethis SO answer所示:

For Django 1.7+, use JsonResponse as shown in this SO answer like so :

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

这篇关于使用 Django 和 Python 创建 JSON 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆