我试图将服务器端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数组)。我还不能解决这个问题。但是我想我对“回声”做错了什么。
我通常使用字典而不是列表来返回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,如下所示:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
我用这个,效果很好。
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"})
如何使用谷歌应用程序引擎与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代码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>
这在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')
使用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'})
首先导入这个:
from django.http import HttpResponse
如果你已经有JSON:
def your_method(request):
your_json = [{'key1': value, 'key2': value}]
return HttpResponse(your_json, 'application/json')
如果你从另一个HTTP请求得到JSON:
def your_method(request):
response = request.get('https://www.example.com/get/json')
return HttpResponse(response, 'application/json')
这些答案大多已经过时了。不建议使用JsonResponse,因为它转义字符,这通常是不希望的。以下是我使用的方法:
views.py(返回HTML)
from django.shortcuts import render
from django.core import serializers
def your_view(request):
data = serializers.serialize('json', YourModel.objects.all())
context = {"data":data}
return render(request, "your_view.html", context)
views.py(返回JSON)
from django.core import serializers
from django.http import HttpResponse
def your_view(request):
data = serializers.serialize('json', YourModel.objects.all())
return HttpResponse(data, content_type='application/json')
Vue用户的奖金
如果你想把你的Django Queryset引入Vue,你可以做下面的事情。
template.html
<div id="dataJson" style="display:none">
{{ data }}
</div>
<script>
let dataParsed = JSON.parse(document.getElementById('dataJson').textContent);
var app = new Vue({
el: '#app',
data: {
yourVariable: dataParsed,
},
})
</script>