Use the Jquery.form plug-in to achieve the perfect form asynchronous submission _web and framework

Source: Internet
Author: User
Tags commit jquery library

Http://www.cnblogs.com/heyuquan/p/form-plug-async-submit.html


Sample downloads: Use the Jquery.form plug-in to implement the perfect form asynchronous submission. rar

Catch the tail of the June, today's theme is

Today I would like to introduce a Jquery plug-ins: Jquery.form.js official website.

Through the plug-in, we can very simple implementation of the form of asynchronous submission, and implementation of file upload, progress bar display, and so on.

Now we start with a asp.net sync form submission and then convert it to an asynchronous form submission. I've written 3 forms to submit examples and have a simple analysis of the pros and cons of various ways.

Of course, the theme is to use the jquery form plug-in easy to implement the form asynchronous submission and analysis of the source code of the plug-in.

Asp. NET Server-side control to implement synchronous form submission

         asp. NET server controls are labeled with IDs and runat= "server" attributes, which output similar <input type= "hidden" name= "__viewstate" id= "__viewstate" in the Customer page content. Value= "/wepdwujnzgzndmwntmzzgr/8zxom5tn0sfhnjaqe12hkqqjtq==" > Label for storing control value data. as follows: 1 2 3 4 5 6 7 8 9 A < form  runat= "server" id= "Server_form" method= "POST" >  &nbs p;   < table  border= "1" >          < tr >               < td > User name: </td >               < td >                   < asp:textbox  id= "Txtloginname" runat= "Server" Autopostback= "true" ></Asp:textbox >               </td >        &nbsP </TR >          < tr >               < td  colspan= "2" style= "Text-align:center" >                  < asp:button  id= "Btnsubmit" runat= text= server Control synchronous commit mode/>                  < asp:button  id= "Btnunsubmit" runat= "Server" onclientclick= "return false;" Text= "Do not submit form"/>              </td >           </tr >      </table > </form > < as p:label  id= "Labresponse" runat= "Server" ></Asp:label >

We built a form with the ASP.net server control, which is defined in the ASP.net page:

1 A page can have only one server-side form tag, and other server-side controls are in the form.

2 The server-side control event in the server-side form on the page that causes the page postback will touch the publication submission event submit. Like what:

A) Click a server-side button control that does not return false in the OnClientClick event

b The page postback is triggered when the value of a server-side control, such as a TextBox, RadioButton, CheckBox, DropDownList, is set to true AutoPostBack.

c) In addition: Type= "submit" Customer service end tag <input type= "submit"/> resulting form submission

This scenario benefits:

1 we can very easily in the background to get the value of the server-side control, such as using this. Txtloginname.text access the value of the control or get the form element value in this.Context.Request based on the form submission method.

2 we can easily set the value of the page server-side control in the background, such as using this. Labresponse.text = "Form Submit successfully".

Disadvantage of this scenario:

The disadvantage is obvious, inefficient, every time the resulting page postback will trigger the full ASP.net page life cycle, resulting in a "white page" situation. (See more Description: asp.net page lifecycle diagram of asp.net programming model)

jquery asynchronously submits a form

Now that we're aware that submitting a form in sync will result in a "white page" user experience, well, now I'm using the last shared technology, "touch jquery:ajax Asynchronous Detail," to adjust the above synchronized submit form to the way it asynchronously submits the form. 1 2 3 4 5 6 7 8 9 id= "Form1" method= "post" >    &n "form ". Bsp < table  border= "1" >          < tr >               < td > User name: </td >               < td >                   < input  type= "text" name= "LoginName"/></td >           </tr >          < TR >              < td > Love   Good: </td >              < td >                  < input  type= " CheckBox "Name=" Cbloveyy "value=" 1 "/> Swimming                   < input  type= "checkbox" Name= "Cbloveyx" value= "1"/> Game    & nbsp;             < input  type= "checkbox" Name= "Cbloveps" value= "1"/> Mountain climbing              </TD >          </tr >           < tr >              < td  colspan= "2 "Style=" Text-align:center >                   < input  id= "Btnajaxsubmit" type= "Submit" value= "Jquery.ajax submit"/>p;            </td >           </tr >      </table > </form >

jquery submits the code as follows: 1 2 3 4 5 6 7 8 9 <script type= "Text/javascript" >    &nbsp ; $ (document). Ready (function  () {         $ ("#btnAjaxSubmit"). Click ( function  () {             var  options = {                  URL: ' async_ Submit_test1.aspx?action=saveuserinfo ',                   type: ' Post ',                   dataType: ' Text ',                   Data: $ ("#form1"). Serialize (),                   success:function  (data) {                      if  (data.length > 0)                           $ ("#responseText"). Text (data);                 }              };              $.ajax (options);              return  false;         });     }); </script>

We pass the $ ("#form1"). Serialize () Converts the data of the form element into a string, and then executes the asynchronous request resource through $.ajax ().

Scenario: Jquery.ajax () +. aspx request

This scenario benefits:

1 We do not feel the page "flash" effect

2 We do not have a "hundreds of pages" of bad user experience because of the server's time-consuming response.

Disadvantage of this scenario:

1 in this scenario I still use the ASPX page to respond to the request, but in the background through the action parameters to do the appropriate processing, although it is asynchronous operation but finished the full run ASP.net page life cycle (this is also in Response.Write () You must call Response.End () after you have finished outputting your own things, or you can terminate the lifecycle prematurely, otherwise the page information will be returned together.

2 The jquery library provides a serialization form string method that cannot collect file-uploaded form elements, such as $ ("#form1"). Serialize (). Therefore, we also need to submit the form via <iframe> analog asynchronous form for the forms containing file uploads. (<iframe> the process of simulating asynchronous form submission I will explain in the source section of the analysis Jquery.form plug-in)

(The Elements property of the form when the data source of the serialized string is provided by the jquery library, and <input type= the table cell of the "file"/> is not included in the elements)

Of course Jquery.ajax () can also combine. ashx files (general processing files) or other ways to implement efficient asynchronous requests, just to illustrate the fact that the asynchronous request ASPX page also runs on the side of the ASPX page life cycle.

Jquery.form plug-in easy Implementation form submission

Now we use jquery's form plug-in Jquery.form.js (official website) to implement the asynchronous form submission.

1 The plugin needs jquery minimum version for v1.5

2 The plugin provides the Ajaxsubmit and ajaxform two forms submission, but do not use the same two ways for the same form.

I will now implement an efficient asynchronous form submission through the Jquery+jquery.form plugin +ashx (General processing file). 1 2 3 4 5 6 7 8 9 < form  id= "Form1" action= "Ajaxoperation.ashx" method= "POST" >  & nbsp;   < table  border= "1" >          < caption > JQuery.form.js Asynchronous Submit Mode </caption >          < tr >               < td > User name: </td >               < td >                   < input  type= "text" name= "LoginName"/></td >          </TR >          < tr >              < td  colspan= "2" style = "Text-align:center";                  < button   id= "Btnajaxsubmit" >ajaxsubmit submit </button >                   &nbsp;                  < input   id= "Btnajaxform" type= "Submit" value= "Ajaxform submit"/>               </td >          </TR >       </table > </form >

1 specifies an action value for the <form> tag, specifying that the form request be processed using AJAXOPERATION.ASHX.

2 using the two submit buttons Btnajaxsubmit and Btnajaxform correspond to the two form submission APIs provided by the Jquery.form plug-in respectively.

jquery Form plug-in submit code as follows: 1 2 3 4 5 6 7 8 9 <script type= "Text/javascript" >    &nbs P $ (document). Ready (function  () {     var  options = {     & nbsp;   success:function  (data) {              $ ("#responseText"). Text (data);         }     };           //Ajaxform           $ ("#form1"). Ajaxform (options);           //Ajaxsubmit           $ ("#btnAjaxSubmit"). Click (function  () {          & nbsp;  $ ("#form1"). Ajaxsubmit (options);         });     }); </script>

Scheme: JQuery.form.js plugin +. ASHX Request

This scenario benefits:

1 simply a few lines of code, we can implement the form of submission, and flexible through the ajaxsubmit () function based on any event trigger to implement the form asynchronous submission.

2 support file Upload function, and support progress bar update in new browser. (In the Jquery.form plug-in source code analysis will be described)

3 The perfect combination with the jquery library, supports the various events triggered by the Jquery.ajax () function, and supports the parameters passed in the Jquery.ajax (). (In the Jquery.form plug-in source code analysis will be described)

OK, so short and easy to read code, such a lazy way is not what we pursue. The form submission API provided by the Jquery.form plugin is efficient. What's going on inside. Then follow me to see Jquery.form plug-in internal implementation bar ...

Jquery.form Plug-in Source code analysis

Jquery.form Plug-ins (Jquery.form.js official website), can let us very simple to implement the form of asynchronous submission, file upload, progress bar display and so on.

1. $ ("Form1"). Ajaxsubmit (Options)

1 Ajaxsubmit is the core function of the jquery form plug-in. Very flexible because it relies on the event mechanism to submit the form using Ajaxsubmit () as long as an event is triggered, eg: hyperlinks, pictures, click events for buttons.

2 Options parameter is

A) a function, then the callback function called after the form was submitted successfully, that is, options={success:function}.

b The options parameter is a set, and a parameter key value pair

Key Name

Describe

Type

(Default is the method property value of the form, if no fetch is set)

Type of request, for example: POST, get, put, and propfind. Not sensitive to case.

Url

(Default takes the Action property value of the form, if the default fetch WINDOW.LOCATION.HREF is not set)

The URL address of the request, which can be either an absolute address or a relative address.

Data

(An object member must contain the name and Value property) to provide an additional data object that returns the serialized string through the $.param () function, which is later spliced into the string that is serialized by the form element.

Extradata

(This parameter is not externally available and is handled internally)

This parameter is a copy of data before it is serialized as a string, used only to contain <input type= "file"/> in the form and is the old browser.

Because in the old browser file upload file We need to simulate asynchronous commit via <iframe>, at this time Extradata will be converted to <input type= "hidden"/> elements are included in the form and submitted to the server together.

DataType

Generally do not need to set their own. parameter function Please see: "Jquery.ajax ()-datatype"

Traditional

If you want to serialize data in a traditional way, set it to true. Please refer to the $.param () depth recursive detailed.

Delegation

(Applies to Ajaxform) Ajaxform delegate mode that supports the jquery plug-in (requires jquery v1.7+), so when you call ajaxform its form form does not necessarily exist, But dynamically constructed form will invoke ajaxsubmit at the appropriate time. Eg:1 2 3 4 $ (' #myForm '). Ajaxform ({delegation:true, target: ' #output '});

Replacetarget

(default: false) works together with the target parameter, true executes the REPLACEWIRH () function, and false executes the HTML () function

Target

Provides an HTML element that, when the request "succeeds" and the datatype parameter is not set, the returned data replacewith () or HTML () drops the original contents of the object, and then traverses the object call success callback function.      1 2 3 4 5 6 7 if (!options.datatype && options.target) {var oldsuccess = Options.success | | function () {}; Callbacks.push (function (data) {var fn = Options.replacetarget?          ' replacewith ': ' HTML ';      $ (Options.target) [FN] (data). Each (oldsuccess, arguments); }); }

Includehidden

After the request succeeds, setting the Execute ClearForm () function to empty the form element determines how to empty the hidden field elements according to the Includehidden setting.

1 passes true to indicate that all hidden field elements of the form are emptied. <

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.