使用Django和Python创建JSON响应我正在尝试将服务器端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数组)。我还不知道这个问题。但我觉得我对“回声”做错了什么。
3 回答
慕斯709654
TA贡献1840条经验 获得超5个赞
import jsonfrom django.http import HttpResponseresponse_data = {}response_data['result'] = 'error'response_data['message'] = 'Some error message'
return HttpResponse(json.dumps(response_data), content_type="application/json")
JsonResponse
from django.http import JsonResponsereturn JsonResponse({'foo':'bar'})
慕勒3428872
TA贡献1848条经验 获得超6个赞
from django.http import JsonResponsereturn JsonResponse({'foo':'bar'})
ibeautiful
TA贡献1993条经验 获得超5个赞
from django.utils import simplejsonfrom django.http import HttpResponsedef some_view(request): to_json = { "key1": "value1", "key2": "value2" } return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
from django.utils import simplejsonclass 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, )
from django.http import JsonResponsedef some_view(request): return JsonResponse({"key": "value"})
添加回答
举报
0/150
提交
取消