Notes:
1. The submit button in layui is implemented based on the "listening" mechanism.
2. The call to form.on() needs to be placed in the callback function of layui.use.
3. The 'return false' at the end is indispensable to ensure that the page refresh will not be triggered. Note that it must be 'return false', not simply 'return'.
Capturing form data can be achieved in four steps:
1. Disable the button. To prevent users from clicking continuously, please note that the button should be explicitly enabled again after the Ajax request is completed (complete).
2. Integrate form data. Many times, in addition to obtaining the data from the formal form, some additional data needs to be appended.
3. Determine the path. Sometimes, the same button can express multiple operations, such as adding or modifying.
4. Initiate a request. Initiate an Ajax request, pass parameters to the server, and process the return value in the callback function.
5.return false.
Important Code List
1. HTML Statement
<form class="layui-form"> <input type="hidden" name="id" /> <button class="layui-btn layui-btn-sto" id="btnSave" lay-filter="btnSave" lay-submit>保存</button> </form>
If you only need to listen for effects (click events), you only need one of the above buttons and lay-filter and lay-submit.
If you need to collect the values of form elements, you also need form and its style layui-form.
2. js event monitoring
// 保存 form.on('submit(btnSave)', function (data) { console.info('开始保存'); // * 按钮禁用 var isDisabled = $("#btnSave").hasClass('layui-btn-disabled'); if (isDisabled) { return false; } // * 整合表单数据 var formData = data.field; $.extend(formData, { Id: $("#hiddenId").val() }); console.info(formData); // * 确定路径 var url = ""; if (editMode == "add") { url = urlEnum.Add; } else if (editMode == "update") { url = urlEnum.Update; } else { alert('编辑模型不确定, add / update'); return; } // * 发起请求 $.ajax({ data: formData, type: "POST", dataType: "JSON", url: url, beforeSend: function () { // 禁用 $("#btnSave").addClass('layui-btn-disabled'); }, complete: function () { // 启用 $("#btnSave").removeClass('layui-btn-disabled'); }, success: function (result) { console.info("保存数据成功,返回的数据为:↓ "); console.info(result); if (result.Status) { // 刷新列表 parent.$("#mainGrid").bootstrapTable("selectPage", 1); // 确保在最后关闭窗体 parent.layer.close(parent.layer.getFrameIndex(window.name)); } else { // 提示失败 layer.alert(result.StatusMessage, { title: '提示信息', icon: 5 }); } } }); // end ajax return false; });
For more layui related knowledge, please pay attention to layui framework.
The above is the detailed content of layui captures form data. For more information, please follow other related articles on the PHP Chinese website!