场景
此时我的表单中有一排开关
数据库有一排状态
需求是要当开关开启时数据库state
为1,关闭时为0
初始的视图层
将整个adv数据表返回给前端HTML
def adv(request):adv_list = Adv.objects.all()return render(request, 'adv.html', locals())
HTML部分
- 当adv的状态为0时默认开关关闭,反之当state不为0时开关默认开启
{# 广告开关 #}
<td>{% if adv.state %}<form class="layui-form" action=""><div class="layui-form-item"><input type="checkbox" name="open" lay-skin="switch" lay-filter="switchTest"title="ON|OFF" data-state-name="{{ adv.title }}" data-state-id="{{ adv.id }}"checked></div></form>{% else %}<form class="layui-form" action=""><div class="layui-form-item"><input type="checkbox" name="open" lay-skin="switch" lay-filter="switchTest"title="ON|OFF" data-state-title="{{ adv.title }}"data-state-id="{{ adv.id }}"></div></form>{% endif %}
JS代码
form.on('switch(switchTest)', ...)
:这是Layui库中用于监听开关元素状态变化的方法。switchTest
是一个过滤器,用于指定要监听的开关元素function (data) { ... }
:这是事件处理程序函数,当开关元素的状态发生变化时,该函数会被调用。data
是一个参数,用于接收传递给事件处理程序的数据对象const stateName = $(data.elem).data('state-name')
const stateId = $(data.elem).data('state-id')
用于获取开关上的两个自定义参数,此处表示adv表的id
字段和title
字段$(data.elem)
:通过$(...)
语法,将data.elem
转换为jQuery对象,以便使用jQuery的相关方法- 最后将id传回后端
{# 控制开关 #}
var form = layui.form
form.on('switch(switchTest)', function (data) {const stateTitle = $(data.elem).data('state-title')const stateId = $(data.elem).data('state-id')layer.msg(stateTitle + '广告::' + (this.checked ? '开启' : '关闭'), {offset: '6px'});if (this.checked) {$.ajax({url: '{% url 'Blog:adv_state' %}',type: 'post',contentType: 'application/json',data: JSON.stringify({'stateId': stateId, 'state': 1}),})} else {$.ajax({url: '{% url 'Blog:adv_state' %}',type: 'post',contentType: 'application/json',data: JSON.stringify({'stateId': stateId, 'state': 0}),})}
})
视图层接受部分
- 接受id然后根据id去修改state状态
def adv_state(request):if request.method == 'POST' and request.is_ajax:data = json.loads(request.body)print(f'开关数据:{data}')stateId = data['stateId']state = data['state']adv_obj = Adv.objects.get(id=stateId)adv_obj.state = stateadv_obj.save()return HttpResponse('ok')