Use Ajax to submit form forms, including Ajax file uploads

Source: Internet
Author: User
Tags html page json prepare
use Ajax to submit form forms, including Ajax file uploadsHttp://www.cnblogs.com/zhuxiaojie/p/4783939.html
Preface

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 form = new FormData ();
          Form.append ("username", "zxj");
          Form.append ("password", 123456);
          var req = new XMLHttpRequest ();
          Req.open ("Post", "${pagecontext.request.contextpath}/public/testupload", 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",
                type: "Post",
                Data:form,
                Processdata:false,
                Contenttype:false,
                success:function (data) {
                    window.clearinterval (timer);
                    Console.log ("over..");
                }
);

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

You think it's 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:

        function test () {
            var form = new FormData (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: The ID name must be written like this, or it will be error-
    <bean id= "Multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver ">
        <property name=" Defaultencoding " Value= "UTF-8" ></property>
        <property name= "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: The Action property value of the form
type Specifies the method by which the form data is submitted: "GET" or "POST". default: 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: null
Success The callback function that was called after the form was successfully committed. The datatype option value then determines whether to return ResponseText or responsexml values. default: null
dataType One of the data types returned: null, XML, script, JSON. default value: null
resetform Indicates whether the form submission succeeds if it is reset. default: null
clearform Indicates whether form data is purged if the form is submitted successfully. default value: null
Related Article

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.