layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and AJAX request parameters, and listening to form submission events to obtain data.
How layui gets form data
layui provides several methods to get form data:
1. layui.form.val(form selector)
This is a convenient method to directly obtain all field data of the entire form.
<code class="javascript">layui.form.val('form selector', { name: 'value', ... });</code>
2. lay() method
The lay() method can get the value of a single form element and needs to pass the element's ID or DOM object.
<code class="javascript">const value = $('#input-id').val();</code>
3. formAPI.getVal() method
The getVal() method provided by formAPI can get the value of the specified field in the form.
<code class="javascript">const formAPI = layui.form.render('form selector'); const value = formAPI.val('field-name');</code>
4. layui.request() method
layui.request() method can serialize form data into a string and serve as parameters for AJAX requests.
<code class="javascript">layui.request.post('/submit_form', { data: $('#form').serialize() });</code>
5. layui.form.on('submit()', callback)
Listen to the form submission event and obtain the form data in the callback function.
<code class="javascript">layui.form.on('submit(submit-btn)', function(data) { console.log(data.field); // 表单字段数据 });</code>
According to your needs, you can choose one or more of the above methods to obtain layui form data.
The above is the detailed content of How to get form data in layui. For more information, please follow other related articles on the PHP Chinese website!