案例

第一步:导入layui+ajax的js文件以及css文件

{% block title %}自动化测试平台{% endblock %}

{#引入layui.css#}

{#引入layui.js#}

第二步:编写表单

action=“” method=“post” button控件必须包含lay-submit=“” lay-filter=""两个公用属性

{# #}

{% csrf_token %}

class="layui-input">

class="layui-input">

{# #}

{% if alert_msg %}

提示信息:{{ alert_msg }}

 

{% endif %}

第三步:编写接口

@csrf_exempt

def add_project(request):

arg = {"status": "ok", "msg": None}

pro_obj = ProjectManage()

try:

if request.is_ajax():

print(request.POST)

pro_name = request.POST['pro_name']

pro_en_name = request.POST['pro_en_name']

pro_remark = request.POST['pro_remark']

msg = pro_obj.func_add_project(pro_name, pro_en_name, pro_remark)

arg['state'] = msg

# return redirect('autotest:project_list')

return JsonResponse(arg)

else:

return render(request,'add_project.html')

except Exception as e:

arg['code'] = "error"

arg['msg'] = e

return JsonResponse(arg)

第四步:编写form表单的js

问题分析

(1) ajax未执行 由于没有导入jquery.js文件导致的 (2)会同时发送一个post请求和get请求 由于form表单没有设置method=“post” ,以及action不为空 (3)ajax回调函数获取不到响应数据 django编写的接口的返回的数据格式不正确导致

文章链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: