JQuery form plug-in ajaxform usage details

Li gulare 2020-11-12 23:50:07
jquery form plug-in plug ajaxform


Plug in main method :

ajaxForm
ajaxSubmit
formToArray
formSerialize

fieldSerialize
fieldValue
clearForm
clearFields
resetForm

 

Sample code :

?
1
2
3
4
5
6
7
// wait for the DOM to be loaded
$(document).ready( function () { 
    // bind 'myForm' and provide a simple callback function  
    $( '#myForm' ).ajaxForm( function () {  
        alert( "Thank you for your comment!" ); 
     });
});

Download address : http://malsup.github.com/jquery.form.js

Form plugin API

The original English text :http://www.malsup.com/jquery/form/#api

Form plugin API There are several ways , Make it easy to manage form data and submit forms .

ajaxForm()

Add all required event listeners , by AJAX Submit the form ready .ajaxForm Cannot submit form . stay document Of ready Function , Use ajaxForm for AJAX Submit the form for preparation .ajaxForm Accept 0 Or 1 Parameters . This single parameter can be a callback function , It can also be a Options object .
Linkable (Chainable): Sure .

example :

$('#myFormId').ajaxForm();

ajaxSubmit()

Immediately by AJAX To submit a form . Most of the time , All calls ajaxSubmit To respond to user submitted forms .ajaxSubmit Accept 0 Or 1 Parameters . This single parameter can be a callback function , It can also be a Options object .
Linkable (Chainable): Sure .

example :

?
1
2
3
4
5
6
7
8
9
// Bind form submit event handler
$( '#myFormId' ).submit( function () {
     // Submit Form
     $( this ).ajaxSubmit();
     // To prevent normal browsers from submitting forms and generating page navigation ( Prevent page refresh ?) return false
     return false ;
    });
 
formSerialize()

Serialize forms ( Or serialize ) Make a query string . This method will return a string of the following format :name1=value1&name2=value2.
Linkable (Chainable): You can't , This method returns a string .

example :

var queryString = $('#myFormId').formSerialize();

//  Now you can use $.get、$.post、$.ajax Wait to submit the data
$.post('myscript.php', queryString);

fieldSerialize()

Serialize the form's field elements ( Or serialize ) Make a query string . When only some form fields need to be serialized ( Or serialize ) when , This is convenient . This method will return a string of the following format :name1=value1&name2=value2.
Linkable (Chainable): You can't , This method returns a string .

example :

var queryString = $('#myFormId .specialFields').fieldSerialize();


fieldValue()

Returns the value of the form element that matches the insert array . from 0.91 From Edition , This method will always return data as an array . If the element value is judged to be invalid , Then the array is empty , Otherwise it will contain one or more element values .
Linkable (Chainable): You can't , This method returns an array .

example :

//  Get the password input value
var value = $('#myFormId :password').fieldValue(); 
alert('The password is: ' + value[0]); 


resetForm()

By calling the original DOM Method , Restore the form to its original state .
Linkable (Chainable): Sure .

example :

$('#myFormId').resetForm();


clearForm()

Clear form elements . This method takes all the text (text) Input field 、 password (password) Input fields and text fields (textarea) Field is empty , Remove any select Selection of elements , And put all the radio options (radio) Buttons and multiple choices (checkbox) Button reset to unselected .
Linkable (Chainable): Sure .

$('#myFormId').clearForm();


clearFields()

Clear field elements . Only when some form elements need to be cleared is it convenient to use .
Linkable (Chainable): Sure .

$('#myFormId .specialFields').clearFields();

Options object

ajaxForm and ajaxSubmit It supports many options parameters , These option parameters can use a Options Object to provide .Options Just one. JavaScript object , It contains the following sets of properties and values :

target

Indicates the elements in the page that are updated by the server response . The value of the element may be specified as a jQuery Selector string , One jQuery object , Or a DOM Elements .
The default value is :null.

url

Specify the URL.
The default value is : Form action Property value

type

Specify how to submit form data (method):“GET” or “POST”.
The default value is : Form method Property value ( If the default is not found “GET”).

beforeSubmit

Callback function called before form submission .“beforeSubmit” Callback function as a hook (hook), It is provided to run pre submission logic or verify form data . If “beforeSubmit” Callback function return false, Then the form will not be submitted .“beforeSubmit” The callback function takes three call parameters : Array form data ,jQuery Form object , And the introduction ajaxForm/ajaxSubmit Medium Options object . The form array accepts data in the following ways :

[ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]

The default value is :null

success

Callback function invoked after the form is submitted successfully . Provided “success” Callback function , When a response is returned from the server, it is called . Then from dataType The option value determines to return responseText still responseXML Value .
The default value is :null

dataType

Expected data type returned .null、“xml”、“script” perhaps “json” One of them .dataType Provide a way , It specifies how to handle the response of the server . This is directly reflected in jQuery.httpData Method to go . The following values are supported :

'xml': If dataType == 'xml', The server response will be taken as XML To treat . meanwhile , If “success” The callback method is specified , Will send back responseXML value .

'json': If dataType == 'json', The server response will be evaluated , And deliver it to “success” The callback method , If it's designated .

'script': If dataType == 'script', The server response will be evaluated as plain text .

The default value is :null( Server return responseText value )

semantic

Boolean flag indicating whether data must be submitted in strict semantic order (slower). Note that the normal form serialization is done in semantic order with the exception of input elements of type="image". You should only set the semantic option to true if your server has strict semantic requirements and your form contains an input element of type="image".
The Boolean sign , Indicates whether the data must be in strict semantic order (slower?) To submit . Be careful : Generally speaking , Forms have been serialized in semantic order ( Or serialize ), except type="image" Of input Elements . If your server has strict semantic requirements , And the form contains a type="image" Of input Elements , It's time to semantic Set to true.( Translation notes : This passage is incomprehensible , The translation may not convey the meaning , But please correct me .)
The default value is :false

resetForm

The Boolean sign , Indicates whether to reset the form if it is submitted successfully .
Default value: null

clearForm

The Boolean sign , Indicates whether to clear the form data if the form is submitted successfully .
The default value is :null

example :

//  Get ready Options object

?
1
2
3
4
5
6
7
8
9
var options = {
     target:      '#divToUpdate' ,
     url:         'comment.php' ,
     success:  function () {
       alert( 'Thanks for your comment!' );
     } };
 
    // take options Pass to ajaxForm
$( '#myForm' ).ajaxForm(options);


Be careful :Options Objects can also be used to pass values to jQuery Of $.ajax Method . If you are familiar with $.ajax Supported by the options, You can use them to Options Object passed to ajaxForm and ajaxSubmit.

ajaxForm() It is applicable to processing in form submission mode ajax technology ( Need to provide form action、id、 method, It's best to provide submit Button ) It greatly simplifies the use of ajax Data transfer problem when technology submits form , Use ajaxForm() You don't have to do it one by one JavaScript To get the value of each form property , And it doesn't need to pass after the request path url Rewrite the way to transfer data .ajaxForm() The values of each attribute in the current form are automatically collected , Then submit it to the target as a form submission url. It's safer to submit data in this way , And it's easier to use , Don't write too much redundancy JavaScript Code

$(document).ready(function(){

         registerForm' Forms id

data Callback data

        $('#registerForm').ajaxForm(function(data){

            alert(data);// eject ajax Callback result after request

        });

});

ajaxSubmit() It is applicable to the mechanism of events ajax Submit form Forms ( Hyperlinks 、 The image click event ), The effect of this method is ajaxForm() similar , But it's more flexible , Because he depends on the event mechanism , This method can be used as long as there are events . You just need to specify the form Of action Attribute is enough , There is no need to provide submit Button .

$(document).ready(function(){

    $('#btn').click(function(){

            $('#registerForm').ajaxSubmit(function(data){

                alert(data);

            });

            return false;

    });

    });

This code is used in the form id by btn The button click The event is triggered by ajaxSubmit() Methods to ajax Technology submit form to form action The path indicated

formSerialize() Is the one form All form elements in the name As key,value Serialization as values , This requires that you set the form elements for each form element name Properties and fill form elements value Value , It's better to set id convenient jquery Locate form elements . To use this method you must set the form element name Properties and fill form elements value Value , I forgot to set it up when I first used it name attribute , Finally, I found this mistake with the help of my colleagues for a long time .

var str=$('#registerForm').formSerialize(); // registerForm by form id

alert(str);

fieldSerialize() Yes, it will form Form elements are serialized to name As key,value Serialization as values , This requires that you set the form elements for each form element name Properties and fill form elements value Value .

var str=$('#username). fieldSerialize();

alert(str);

版权声明
本文为[Li gulare]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考->实现->不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple