我试图将服务器端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数组)。我还不能解决这个问题。但是我想我对“回声”做错了什么。


当前回答

def your_view(request):
    response = {'key': "value"}
    return JsonResponse(json.dumps(response), content_type="application/json",safe=False)

#指定content_type并使用json.dump() son作为不作为对象发送的内容

其他回答

如何使用谷歌应用程序引擎与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)
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)

对于使用Django 1.7+的用户

from django.http import JsonResponse

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

官方文档

通过这种方式,json内容可以作为具有特定文件名的文件下载。

import json
from django.http import HttpResponse

def download_json(request):
    data = {'some': 'information'}

    # serialize data obj as a JSON stream 
    data = json.dumps(data)
    response = HttpResponse(data, content_type='application/json charset=utf-8')

    # add filename to response
    response['Content-Disposition'] = 'attachment; filename="filename.json"'
    return response

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

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

你甚至不需要json。转储数组。