from django.http import JsonResponse
def test(request):
result = {"status":"错误","data":"","city":"北京"}
return return JsonResponse(result)
上述代码容易乱码,改成以下中文成功
from django.http import HttpResponse
import json
def test(request):
result = {"status":"错误","data":"","city":"北京"}
#json返回为中文
return HttpResponse(json.dumps(result,ensure_ascii=False),content_type="application/json,charset=utf-8")
下面是交互的类型
from django.shortcuts import render
def main_page(request):
return render(request, 'index.html')
#########################html#################################
from django.shortcuts import render
def main_page(request):
data = [1,2,3,4]
return render(request, 'index.html', {'data': data})
#########################js#################################
# -*- coding: utf-8 -*-
import json
from django.shortcuts import render
def main_page(request):
list = ['view', 'Json', 'JS']
return render(request, 'index.html', {
'List': json.dumps(list),
})
#views.py中返回的函数中的值要用 json.dumps() 处理
#在网页上要加一个 safe 过滤器。
var List = {{ List|safe }};
######################网页前台使用Ajax发送请求,后台处理数据后返回数据给前台,前台不刷新网页动态加载数据#############################3
def scene_update_view(request):
if request.method == "POST":
name = request.POST.get('name')
status = 0
result = "Error!"
return HttpResponse(json.dumps({
"status": status,
"result": result
}))
js
function getSceneId(scece_name, td) {
var post_data = {
"name": scece_name,
};
$.ajax({
url: {% url 'scene_update_url' %},
type: "POST",
data: post_data,
success: function (data) {
data = JSON.parse(data);
if (data["status"] == 1) {
setSceneTd(data["result"], scece_name, td);
} else {
alert(data["result"]);
}
}
});
}