使用Django和Python创建JSON响应
我试图将服务器端Ajax响应脚本转换为Django HttpResponse,但显然它不起作用 这是服务器端脚本:使用Django和Python创建JSON响应,python,django,json,Python,Django,Json,我试图将服务器端Ajax响应脚本转换为Django HttpResponse,但显然它不起作用 这是服务器端脚本: /* RECEIVE VALUE */ $validateValue=$_POST['validateValue']; $validateId=$_POST['validateId']; $validateError=$_POST['validateError']; /* RETURN VALUE */ $arrayToJs = array(); $arrayToJs[0] =
/* 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.
}
}
}
我使用simplejson对Python列表进行编码(因此它将返回一个JSON数组)。我还没弄明白这个问题。但是我认为我对“echo”做了一些错误的处理。我通常使用字典,而不是列表来返回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+,请按如下所示使用:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
我通常使用字典而不是列表来返回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+,请按如下所示使用:
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中,对象已添加到Django框架本身,这使得此任务更加容易:
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
我用这个,效果很好
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中,对象已添加到Django框架本身,这使得此任务更加容易:
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
您需要使用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")
您需要使用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")
使用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)
使用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)
这是我使用基于类的视图的首选版本。 只需将基本视图子类化并重写get()-方法
这是我使用基于类的视图的首选版本。 只需将基本视图子类化并重写get()-方法 并且认为:
resp_data = {'my_key': 'my value',}
return JsonResponse(resp_data)
并且认为:
resp_data = {'my_key': 'my value',}
return JsonResponse(resp_data)
django 1.7中的新功能
可以使用对象
从文档中:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
django 1.7中的新功能
可以使用对象
从文档中:
from django.http import JsonResponse
return JsonResponse({'foo':'bar'})
从Django 1.7开始,您就有了一个完全符合您需要的标准:
from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)
您甚至不需要json.dump您的数组。自从Django 1.7以来,您就有了一个正是您所需要的标准:
from django.http import JsonResponse
...
return JsonResponse(array_to_js, safe=False)
您甚至不需要json.dump数组。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>
$(文档).ready(函数(){
$(“#mySelect”).change(函数(){
selected=$(“#mySelect选项:selected”).text()
$.ajax({
键入:“POST”,
数据类型:“json”,
contentType:'application/json;charset=utf-8',
url:“/view/”,
数据:{
“水果”:已选中
},
成功:功能(结果){
文件写入(结果)
}
});
});
});
{{data}}
选择您喜爱的水果:
挑选水果
苹果
橙色
菠萝
香蕉
Django codeviews.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>
$(文档).ready(函数(){
$(“#mySelect”).change(函数(){
selected=$(“#mySelect选项:selected”).text()
$.ajax({
键入:“POST”,
数据类型:“json”,
contentType:'application/json;charset=utf-8',
url:“/view/”,
数据:{
“水果”:已选中
},
成功:功能(结果){
文件写入(结果)
}
});
});
});
{{data}}
选择您喜爱的水果:
挑选水果
苹果
橙色
菠萝
香蕉
适用于使用Django 1.7的用户+
from django.http import JsonResponse
def your_view(request):
json_object = {'key': "value"}
return JsonResponse(json_object)
适用于使用Django 1.7的用户+
from django.http import JsonResponse
def your_view(request):
json_object = {'key': "value"}
return JsonResponse(json_object)
在视图中,请使用以下命令:
form.field.errors|striptags
要获取视图中没有html的验证消息,请使用以下命令:
form.field.errors|striptags
对于不使用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 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类的视图,您可以编写:
从django.views导入视图
从django.http导入JsonResponse
类JsonView(视图):
def get(自我,请求):
返回JsonResponse({'some':'data'})
使用Django Rest框架,您可以编写:
从rest\u framework.views导入APIView
来自rest\u framework.response导入响应
类JsonView(APIView):
def get(自我,请求):
返回响应({'some':'data'})
使用基于Django类的视图,您可以编写:
从django.views导入视图
从django.http导入JsonResponse
类JsonView(视图):
def get(自我,请求):
返回JsonResponse({'some':'data'})
使用Django Rest框架,您可以编写:
从rest\u framework.views导入APIView
来自rest\u framework.response导入响应
类JsonView(APIView):
def get(自我,请求):
返回响应({'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')
首先导入以下内容:
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
from django.http import JsonResponse
使用JsonResponse
from django.http import JsonResponse
这些答案大多已经过时了。不建议使用JsonResponse,因为它会转义字符,这通常是不需要的。以下是我使用的: views.py(返回HTML) views.py(返回JSON) Vue用户奖金 如果要将Django查询集引入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>
{{data}}
让dataParsed=JSON.parse(document.getElementById('dataJson').textContent);
var app=新的Vue({
el:“#应用程序”,
数据:{
yourVariable:dataParsed,
},
})
这些答案大多已经过时。JsonResp