首页 文章

使用Django和Python创建JSON响应

提问于
浏览
379

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

这是服务器端脚本:

/* 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数组) . 我还无法弄清楚这个问题 . 但我认为我对'回声'做错了 .

13 回答

  • 4

    从Django 1.7开始,你有一个标准JsonResponse,这正是你所需要的:

    from django.http import JsonResponse
    ...
    return JsonResponse(array_to_js, safe=False)
    

    你甚至不需要json.dump你的数组 .

  • 792

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

    import json
    
    from django.http import HttpResponse
    
    response_data = {}
    response_data['result'] = 'error'
    response_data['message'] = 'Some error message'
    

    Pre-Django 1.7你会像这样返回它:

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

    对于Django 1.7,使用JsonResponse,如_394450所示,如下所示:

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

    How to use google app engine with ajax (json)?

    使用JQuery编写Javascript代码:

    $.ajax({
        url: '/ajax',
        dataType : 'json',
        cache: false,
        success: function(data) {
            alert('Load was performed.'+data.ajax_resp);
        }
    });
    

    代码Python

    class Ajax(webapp2.RequestHandler):
    def get(self):
        my_response = {'ajax_resp':'Hello, webapp World!'}
        datos = json.dumps(my_response)
    
        self.response.headers.add_header('content-type', 'application/json', charset='utf-8')
        self.response.out.write(datos)
    
  • 23

    在视图中使用此:

    form.field.errors|striptags
    

    用于获取没有html的验证消息

  • 138
    from django.http import HttpResponse
    import json
    
    class JsonResponse(HttpResponse):
        def __init__(self, content={}, mimetype=None, status=None,
                 content_type='application/json'):
            super(JsonResponse, self).__init__(json.dumps(content), mimetype=mimetype,
                                               status=status, content_type=content_type)
    

    在视图中:

    resp_data = {'my_key': 'my value',}
    return JsonResponse(resp_data)
    
  • 13

    您将要使用django序列化程序来帮助解决unicode问题:

    from django.core import serializers
    
    json_serializer = serializers.get_serializer("json")()
        response =  json_serializer.serialize(list, ensure_ascii=False, indent=2, use_natural_keys=True)
        return HttpResponse(response, mimetype="application/json")
    
  • 10

    使用基于Django类的视图,您可以编写:

    from django.views import View
    from django.http import JsonResponse
    
    class JsonView(View):
        def get(self, request):
            return JsonResponse({'some': 'data'})
    

    使用Django-Rest-Framework,您可以编写:

    from rest_framework.views import APIView
    from rest_framework.response import Response
    
    class JsonView(APIView):
        def get(self, request):
            return Response({'some': 'data'})
    
  • 15

    这是我使用基于类的视图的首选版本 . 简单地将基本视图子类化并覆盖get() - 方法 .

    import json
    
    class MyJsonView(View):
    
        def get(self, *args, **kwargs):
            resp = {'my_key': 'my value',}
            return HttpResponse(json.dumps(resp), mimetype="application/json" )
    
  • 131

    对于那些使用Django 1.7的人

    from django.http import JsonResponse
    
    def your_view(request):
        json_object = {'key': "value"}
        return JsonResponse(json_object)
    

    official docs

  • 3

    我用它,它工作正常 .

    from django.utils import simplejson
    from django.http import HttpResponse
    
    def some_view(request):
        to_json = {
            "key1": "value1",
            "key2": "value2"
        }
        return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
    

    替代方案:

    from django.utils import simplejson
    
    class JsonResponse(HttpResponse):
        """
            JSON response
        """
        def __init__(self, content, mimetype='application/json', status=None, content_type=None):
            super(JsonResponse, self).__init__(
                content=simplejson.dumps(content),
                mimetype=mimetype,
                status=status,
                content_type=content_type,
            )
    

    在Django 1.7中,JsonResponse对象已被添加到Django框架本身,这使得这项任务变得更加容易:

    from django.http import JsonResponse
    def some_view(request):
        return JsonResponse({"key": "value"})
    
  • 3

    django 1.7的新功能

    你可以使用JsonResponse对象 .

    来自文档:

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

    Django代码 views.py

    def view(request):
        if request.method == 'POST':
            print request.body
            data = request.body
            return HttpResponse(json.dumps(data))
    

    HTML code view.html

    <!DOCTYPE html>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("#mySelect").change(function(){
            selected = $("#mySelect option:selected").text()
            $.ajax({
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                url: '/view/',
                data: {
                        'fruit': selected
                      },
                success: function(result) {
                            document.write(result)
                        }
        });
      });
    });
    </script>
    </head>
    <body>
    
    <form>
        {{data}}
        <br>
    Select your favorite fruit:
    <select id="mySelect">
      <option value="apple" selected >Select fruit</option>
      <option value="apple">Apple</option>
      <option value="orange">Orange</option>
      <option value="pineapple">Pineapple</option>
      <option value="banana">Banana</option>
    </select>
    </form>
    </body>
    </html>
    
  • 5

    使用Django 1.7或更高版本非常方便,因为你有JsonResponse类,它是HttpResponse的子类 .

    from django.http import JsonResponse
        def profile(request):
            data = {
                'name': 'Raghav',
                'location': 'India',
                'is_active': False,
                'count': 28
            }
            return JsonResponse(data)
    

    对于旧版本的Django,您必须使用HttpResponse对象 .

    import json
    from django.http import HttpResponse
    
    def profile(request):
        data = {
            'name': 'Raghav',
            'location': 'India',
            'is_active': False,
            'count': 28
        }
        dump = json.dumps(data)
        return HttpResponse(dump, content_type='application/json')
    

相关问题