Use Ajax to submit form forms, including Ajax file uploads

Source: Internet
Author: User

Objective

Using AJAX to request data, many people will, for example, say:

$.post (Path,{data:data},function(data) {    ...},"JSON");

Or is this Ajax

$.ajax ({                URL:"${pagecontext.request.contextpath}/public/testupload",                Type:"POST"  ,                Data:{username:username},                success:function(data) {                    Window.clearinterval (timer);                    Console.log ("over ...." );                },                error:function(e) {                    alert ("Error!! ");                    Window.clearinterval (timer);                }            );        

In the same way, many people will. But the more you write, the more you will find that, although you can avoid refreshing the page, but we have to write a lot of JS come to the data:

var username = $ ("#username"). Val (); var password = $ ("#password"). Val (); ....

If the number is small, then there is nothing, but if the data is very large, it is very troublesome, there is no easy way to do it? There must be some answer! Here are two methods that can greatly improve the efficiency of developers.

Method method One: Use the Formdata object

The Formdata object is an object of HTML5, and some of the mainstream browsers are now compatible. Well, if you say IE8 or something, let's talk about the weather today, I didn't hear it. Oh, open a joke, do not support formdata, you can use method two, the following will be introduced. Then say Formdata, it's a HTML5 JavaScript object, very powerful.

Formdata can create an object in thin air, then add data to it, and then submit it directly without having to write a line of HTML code , as follows:

          var New FormData ();          Form.append ("username", "ZXJ");          Form.append ("password", 123456);           var New XMLHttpRequest ();          Req.open (false);          Req.send (form);

This allows the form data to be sent to the browser , or it can be sent using jquery:

 var  form = new   FormData ();  Form.append ( "username", "zxj" ); Form.append ( "password", 123456);                $.ajax ({url:  "${pagecontext.request.contextpath}/public/testupload"  "POST" false   ContentType:  false   function   (data) {Window.clearinterval (timer); Console.log ( "over.."                ); }});

This also allows you to send data directly to the background.

You think this is over? No! That's just the beginning!!

Second Formdata also support directly from the HTML of the form to generate data, that is, the HTML page already has data, and then Formdata can directly write this form of data to this object, and then directly to the background

The code is as follows, giving the HTML code first:

<form id= "TF" >            <input type= "file" Name= "img"/>            <input type= "text" name= "username"/>            <input type= "button" value= "Lift" onclick= "test ();" />                        </form>

Everyone noticed that there was a file in it!

Yes, Formdata also support the many developers have been plagued by the Ajax upload files, before we upload files, we need to write a form to directly refresh the submission, but here is not required, the following gives the submission code:

        functionTest () {varform =NewFormData (document.getElementById ("TF"));//var req = new XMLHttpRequest ();//Req.open ("Post", "${pagecontext.request.contextpath}/public/testupload", false);//req.send (form);$.ajax ({URL:"${pagecontext.request.contextpath}/public/testupload", type:"POST", Data:form, ProcessData:false, ContentType:false, Success:function(data) {Window.clearinterval (timer); Console.log ("Over.."); }, Error:function(e) {alert ("Error!! ");                Window.clearinterval (timer);                    }            }); Get ();//here is the progress bar for uploading files}

It is so simple, using Formdata, in the construction of this object, the object of the form, as a parameter put in, you can, and then Formdata, will get the form object inside all the parameters, even we in the form, do not need to declare enctype = " Multipart/form-data ", you can submit it directly.

Using Formdata, the first is when the form is submitted, do not need to write a large number of JS to obtain form data, directly to the form object construction on the line. The second is the ability to upload files directly, simple and explosive!

Note: When using Formdata submission, you will notice that the form submitted is the request payload, the specific interested students can own Baidu, it is not before the form data submitted, so the background is to be processed, such as SPRINGMVC need to configure

<!--configuration Nultipartresolver, note: ID name must be written like this, or it will be an error -    <BeanID= "Multipartresolver"class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver">        < Propertyname= "Defaultencoding"value= "UTF-8"></ Property>        < Propertyname= "Maxinmemorysize"value= "10240000"></ Property>    </Bean>

Otherwise you will not receive data, of course, backstage, we do not care here first.

Method Two: Use Jquery.form.js

Jquery.form.js is a powerful form plug-in that provides a wide variety of easy-to-follow methods for form manipulation, with some Jquery.form.js instructions below:

Ajaxform Add all the required event listeners to prepare for the AJAX submission form. Ajaxform cannot submit the form. In the ready function of document, use Ajaxform to prepare the form for the AJAX submission. accepts 0 or 1 parameters. A parameter can be a callback function, or it can be an options object. $ ("#formid"). Ajaxform ();
Ajaxsubmit Submit a form using AJAX. accepts 0 or 1 parameters. A parameter can be a callback function, or it can be an options object.

$ ("#formid"). Ajaxsubmit ();

Or

$ ("#formid"). Submit (function () {

$ (this). Ajaxsubmit ();

return false;

});

Formserialize Serializes (or serialize) a form into a query string. This method returns a string in the following format: Name1=value1&name2=value2. No $ ("#formid"). Formserialize ();
Fieldserialize Serializes (or serialize) the field elements of a form into a single query string. This is handy when only a subset of the form fields need to be serialized (or serializable). Returns a string in the following format: Name=value1&name2=value2. No $ ("#formid. Specialfields"). Fieldserialize ();
Fieldvalue Returns the value of the form element that matches the inserted array. The method returns data in the form of an array. If the element value is determined to be invalid, the array is empty. No $ ("#formid:p assword"). Fieldvalue ();
Resetform Restores the form to its original state. No $ ("#formid"). Resetform ();
ClearForm Clears the form element. This method resets all text, password, textarea, clears the selection in the Select element, and resets all radio and CheckBox buttons to the unselected state. No $ ("#formid"). ClearForm ();
Clearfields Clears the field element. Only some form elements are easy to use when they need to be cleared. No $ ("#formid. Specialfields"). Clearfields ();

Options Object

Both Ajaxform and Ajaxsubmit support a wide range of option parameters, which can be provided using an options object.

Target Indicates the element in the page that is updated by the server response. The value of the element may be specified as a jquery selector string, a jquery object, and a DOM element. Default value: null
Url Specifies the URL to submit the form data. Default value: The Action property value of the form
Type Specifies the method by which the form data is submitted: "GET" or "POST". Default value: GET
Beforesubmit The callback function that was called before the form was submitted. If the callback function returns false, the form will not be committed. The callback function takes three invocation parameters: the form data as an array, the JQuery form object, and the options object in the incoming ajaxform/ajaxsubmit. Default value: null
Success callback function that is called after the form has been successfully committed. The datatype option value then determines whether to return ResponseText or responsexml values. Default value: null
DataType Data type returned: null, XML, script, json one of them. Default value: null
Resetform Indicates whether the form submission succeeds if it is reset. Default value: null
ClearForm Indicates whether the form data is purged if the form submission succeeds. Default value: null

So now for some of its main usage!

It also supports AJAX submissions for a form, and is easier to submit in the following ways:

Html:

<formID= "TF">            <inputtype= "File"name= "img"/>            <inputtype= "text"name= "username"/>            <inputtype= "button"value= "Lift"onclick= "Test ();"/>        </form>

Use the Jquery.form.js form plug-in below to submit the form

$ ("#tf"). Ajaxsubmit ();

Well, it's that simple, you don't ask me why it's so simple, then it's going to put the entire form, as an Ajax to submit, the same, it also supports file upload! For some other usage, please refer to the instructions given above.

Use Ajax to submit form forms, including Ajax file uploads

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.