和田知名网站建设企业,搜索引擎查关键词排名的软件,烟台网站排名优化费用,crm免费版前台通过json 取出后台数据步骤1:后台数据通过 JSON 序列化成字符串注意#xff1a;1、json是1个字符串2、通过json.dumps(xxx) 序列化成 1个字符串的 字典对象views.pydef ajax(request):if request.methodPOST:print(request.POST)data{status:0,msg:请求成功,data:[11,22,3…前台通过json 取出后台数据步骤1:后台数据通过 JSON 序列化成字符串注意1、json是1个字符串2、通过json.dumps(xxx) 序列化成 1个字符串的 字典对象views.pydef ajax(request):if request.methodPOST:print(request.POST)data{status:0,msg:请求成功,data:[11,22,33,44]}return HttpResponse(json.dumps(data))else:return render(request,ajax.html)此时浏览器返回的数据步骤2前台取出后台序列化的字符串方法1正则表达式 (不推荐)方法2jQuery.parseJSON() 需要import json转换成1个JQuery可识别的字典(对象) 通过 对象. xxx 取值 (推荐)views.py序列化return HttpResponse(json.dumps(data))ajax.html 取值var objjQuery.parseJSON(arg)console.log(obj.status)修改后的tempates 中ajax.html 代码function DoAjax(){var temp$(#na).val()$.ajax({url:/ajax/, //url相当于 form 中的 actiontype:POST, //type相当于form 中的 methoddata:{dat:temp}, // data传人的数据 dat为任意设置的内容相当于模版中的{author:lee}success:function(arg){ //成功执行 console.log() 函数 arg 为HttpResponse 返回的值var objjQuery.parseJSON(arg) //转化成JS识别的对象console.log(obj) //打印objconsole.log(arg) //json.dumps(data) 序列化后的数据console.log(obj.status) //取json.dumps(data)字典的值statusconsole.log(obj.msg)console.log(obj.data)console.log(request.POST 提交成功)},error:function(){ //失败console.log(失败)}});}此时前台浏览器 显示数据方法3content_typeapplication/jsonviews.py序列化return HttpResponse(json.dumps(data),content_typeapplication/json)浏览器F12有变色提示或HttpResponse(json.dumps(data),content_typetype/json) 浏览器F12无变色提示ajax.html取值 arg.xxx方法4使用JsonRespon 包 (最简单) 前台通过 arg.xxx 取值views.py 序列化return JsonResponse(data)ajax.html 取值arg.xxx区别HttpResponse 需要dumpsJsonResponse 不需要dumpsviews.pyfrom django.shortcuts import renderfrom django.http import JsonResponsedef ajax(request):if request.methodPOST:print(request.POST)data{status:0,msg:请求成功,data:[11,22,33,44]} #假如传人的数据为一字典#return HttpResponse(json.dumps(data)) #原来写法需要dumpsreturn JsonResponse(data) #后来写法else:return render(request,ajax.html)templates 中的 ajax.htmlfunction DoAjax(){var temp$(#na).val()$.ajax({url:/ajax/, //url相当于 form 中的 actiontype:POST, //type相当于form 中的 methoddata:{dat:temp}, // data传人的数据 dat为任意设置的内容相当于模版中的{author:lee}success:function(arg){ //成功执行 console.log() 函数 arg 为HttpResponse 返回的值//var objjQuery.parseJSON(arg)//console.log(arg) //json.dumps(data) 序列化后的数据console.log(arg.msg)/*console.log(obj)console.log(obj.status) //取json.dumps(data)字典的值statusconsole.log(obj.msg)console.log(obj.data)*/console.log(request.POST 提交成功)},error:function(){ //失败console.log(失败)}});}