template 与 views 沟通 (前端与后端沟通),最终优化版

总共三步:在urls中加入一个path,在views中加入一个function,在template的html中进行post or get;
首先我们来看第一步:
在urls中加一个path,为了方便使用,我们加一个带了option的path,这样就可以一个path做多个事情;
代码:

path('link_db/<str:option>/<str:shedId>/<str:oldPathName>/<str:newPathName>/<str:note>', views.updatePathName, name='updatePathName'),

这里的第一个参数option,就是用来作为选项的;

第二步,在views中实现这个function;
代码:

def updatePathName(request,option,shedId,oldPathName,newPathName,note):    ### update pathname    print('updatePathName',option)    if option == 'updatePathName':        if dbManager.updatePathName(shedId,oldPathName,newPathName):            return JsonResponse({'result':'success','oldpathname': oldPathName,'newpathname':newPathName})        return JsonResponse({'result':'fail','oldpathname': oldPathName,'newpathname':newPathName})        return JsonResponse({'result':'fail'})

把option作为判断条件;
第三步:在html中进行请求:
代码:

function reqListener() {console.log(this.responseText);var response = JSON.parse(this.responseText);// console.log(response);var tmp_res = decodeURI(response['result']);console.log(tmp_res);}//todo send requestsvar oReq = new XMLHttpRequest();oReq.addEventListener("load", reqListener);oReq.open("GET", 'updatePathName' + '/' + shedId + '/' + oldPathName + '/' + newPathName + '/' + 'pengzhen');oReq.send();

另外,如果要使用post的话,这样调用:

var oReq = new XMLHttpRequest();oReq.addEventListener("load", reqListener);// oReq.open("GET", 'decodePathLine_toPolygon' + '/' + pathname + '/' + str_paths);oReq.open("post", 'decodePathLine_toPolygon' + '/' + pathname + '/' + pathname);// const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').valueoReq.setRequestHeader("X-CSRFToken", '{{ csrf_token|safe }}');// oReq.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); oReq.send(str_paths);

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章