2010-03-11 80 views
330

我试图将服务器端Ajax响应脚本转换为Django HttpResponse,但显然它不工作。使用Django和Python创建JSON响应

这是服务器端脚本:

/* 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数组)。我无法弄清楚问题。但我认为我对'回声'做了错误的处理。

+0

您还可以使用Django的恼人的观点装饰者['@ ajax_request'](https://github.com/skorokithakis/django-annoying#ajax_request-decorator)。 – zopieux 2014-04-13 23:22:52

回答

721

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

import json 

from django.http import HttpResponse 

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

前期的Django 1.7你会回到它像这样:

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

Django的1.7+,使用JsonResponse如图this SO answer像这样:

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

正确的+1 - 没有指定mimetype会让你陷入困境 – 2010-03-11 19:50:59

+4

它*是* mimetype,而不是应该让他陷入困境的列表。虽然大多数JSON通常是顶层的对象(“字典”),但JSON对于顶层数组非常满意。 – Thanatos 2012-06-20 21:39:02

+4

对不起,从我写的内容不清楚,但我只是说我使用字典,因为它在将它序列化为JSON时更清晰/更简单。 – Tom 2012-06-21 15:17:59

128

我用这个,它工作正常。

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"}) 
+1

问题是在这里它没有从输入字段获取值vld_value = request.POST.get('validateValue') – Switch 2010-03-11 20:11:42

+1

用Python 2.7,它应该只是“导入json” – 2012-09-06 22:22:35

+0

给我simplejson工作罚款2.7 – Guy 2012-09-18 18:31:18

10

你要使用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") 
+2

这是我的首选版本,但意识到它[只吃Django QuerySets] (http://stackoverflow.com/questions/9061068/django-json-dict-object-has-no-attribute-meta)。 – patroqueeet 2012-12-29 13:25:47

5

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

编写JavaScript代码使用jQuery:

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

这是使用基于类视图我的首选版本。 简单地继承基本视图并覆盖get()方法。

import json 

class MyJsonView(View): 

    def get(self, *args, **kwargs): 
     resp = {'my_key': 'my value',} 
     return HttpResponse(json.dumps(resp), mimetype="application/json") 
15
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) 
+2

只是把默认值content_type ='application/json' – Pol 2013-08-23 20:06:22

126

新在Django 1.7

你可以使用JsonResponse对象。

从文档:

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

一个缺点:它默认为'ensure_ascii',我没有找到一种方法来覆盖它呢。为此创建了一个新问题:http://stackoverflow.com/q/34798703/854477 – 2016-01-14 20:07:52

20
由于

Django的1。7,你有一个标准JsonResponse这就是你需要的东西:

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

你甚至都不需要你传入json.dump阵列。

+0

真棒:D现在,我看到这个我升级到Django 1.7 – 2014-10-30 13:10:43

+0

谢谢你!有用的提示。 – Juergen 2015-01-29 03:37:39

2
Django code(views.py): 


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

HTML代码(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> 
12

对于那些谁使用Django 1.7+

from django.http import JsonResponse 

def your_view(request): 
    json_object = {'key': "value"} 
    return JsonResponse(json_object) 

official docs

1

在查看使用此:

form.field.errors|striptags 

用于获取验证消息没有HTML

3

它非常方便使用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') 
0

随着基于类的Django的意见,你可以这样写:

from django.views import View 
from django.http import JsonResponse 

class JsonView(View): 
    def get(self, request): 
     return JsonResponse({'some': 'data'}) 

与Django的REST的框架,你可以这样写:

from rest_framework.views import APIView 
from rest_framework.response import Response 

class JsonView(APIView): 
    def get(self, request): 
     return Response({'some': 'data'})