django 返回ajax html,Django 前台通过json 取出后台数据
前臺(tái)通過json 取出后臺(tái)數(shù)據(jù)
步驟1:后臺(tái)數(shù)據(jù)通過 JSON 序列化成字符串
注意:1、json是1個(gè)字符串
2、通過json.dumps('xxx') 序列化成 1個(gè)字符串的?'字典對(duì)象'
views.py
def ajax(request):
if request.method=='POST':
print(request.POST)
data={'status':0,'msg':'請(qǐng)求成功','data':[11,22,33,44]}
return HttpResponse(json.dumps(data))
else:
return render(request,'ajax.html')
此時(shí)瀏覽器返回的數(shù)據(jù)
步驟2:前臺(tái)取出后臺(tái)序列化的字符串
方法1:正則表達(dá)式 (不推薦)
方法2:jQuery.parseJSON() ,需要import json
轉(zhuǎn)換成1個(gè)JQuery可識(shí)別的字典(對(duì)象) ? 通過 對(duì)象. xxx 取值 ?(推薦)
views.py序列化:return HttpResponse(json.dumps(data))
ajax.html 取值:var obj=jQuery.parseJSON(arg)
console.log(obj.status)
修改后的tempates 中ajax.html 代碼
function DoAjax(){
var temp=$('#na').val()
$.ajax({
url:'/ajax/', //url相當(dāng)于 form 中的 action
type:'POST', //type相當(dāng)于form 中的 method
data:{dat:temp}, // data:傳人的數(shù)據(jù) dat為任意設(shè)置的內(nèi)容,相當(dāng)于模版中的{author:lee}
success:function(arg){ //成功執(zhí)行 console.log() 函數(shù) arg 為HttpResponse 返回的值
var obj=jQuery.parseJSON(arg) //轉(zhuǎn)化成JS識(shí)別的對(duì)象
console.log(obj) //打印obj
console.log(arg) //json.dumps(data) 序列化后的數(shù)據(jù)
console.log(obj.status) //取json.dumps(data)字典的值status
console.log(obj.msg)
console.log(obj.data)
console.log('request.POST 提交成功')
},
error:function(){ //失敗
console.log('失敗')
}
});
}
此時(shí)前臺(tái)瀏覽器 顯示數(shù)據(jù)
方法3:content_type='application/json'
views.py序列化:return HttpResponse(json.dumps(data),content_type='application/json')
瀏覽器F12有變色提示
或:HttpResponse(json.dumps(data),content_type='type/json') ? 瀏覽器F12無變色提示
ajax.html取值?arg.xxx
方法4:使用JsonRespon 包 (最簡(jiǎn)單) ?前臺(tái)通過 arg.xxx 取值
views.py 序列化:return JsonResponse(data)
ajax.html 取值:arg.xxx
區(qū)別:HttpResponse 需要dumps
JsonResponse 不需要dumps
views.py
from django.shortcuts import render
from django.http import JsonResponse
def ajax(request):
if request.method=='POST':
print(request.POST)
data={'status':0,'msg':'請(qǐng)求成功','data':[11,22,33,44]} #假如傳人的數(shù)據(jù)為一字典
#return HttpResponse(json.dumps(data)) #原來寫法,需要dumps
return JsonResponse(data) #后來寫法
else:
return render(request,'ajax.html')
templates 中的 ajax.html
function DoAjax(){
var temp=$('#na').val()
$.ajax({
url:'/ajax/', //url相當(dāng)于 form 中的 action
type:'POST', //type相當(dāng)于form 中的 method
data:{dat:temp}, // data:傳人的數(shù)據(jù) dat為任意設(shè)置的內(nèi)容,相當(dāng)于模版中的{author:lee}
success:function(arg){ //成功執(zhí)行 console.log() 函數(shù) arg 為HttpResponse 返回的值
//var obj=jQuery.parseJSON(arg)
//console.log(arg) //json.dumps(data) 序列化后的數(shù)據(jù)
console.log(arg.msg)
/*
console.log(obj)
console.log(obj.status) //取json.dumps(data)字典的值status
console.log(obj.msg)
console.log(obj.data)*/
console.log('request.POST 提交成功')
},
error:function(){ //失敗
console.log('失敗')
}
});
}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的django 返回ajax html,Django 前台通过json 取出后台数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: windows安装TeXstudio+M
- 下一篇: web安全后渗透--XSS平台搭建及使用