Ajax (c) Ajax submission form, AJAX implementation file upload

Source: Internet
Author: User
Tags button type file upload json string format


Type one: Use the Targer property of the From form + hidden iframe to achieve similar results, supporting the submission of complex forms containing files and common data
Way two: Use jquery's. Ajax (..), which supports the submission of regular forms, but does not support complex forms containing files; Ajax ({...}), which supports the submission of regular forms, but does not support complex forms containing files; (. Post or. Get bottom-up with. Get bottom-up with. Ajax)
Method Three: Use the jquery plugin ajaxfileupload.js, support uploading files, but do not support the submission of forms
Mode four: Use Jquery.from.js to support the submission of complex forms that contain both files and common data
Four of individuals have used, better like the second and the fourth kind; Use the second to solve the ordinary Ajax request, with the fourth to solve the file upload/form submission; Not much to say, on the code



Mode one: From + iframe
test1.jsp: Form, IFRAME, submit form


<% @ page language = "java" import = "java.util. *" pageEncoding = "UTF-8"%> <! DOCTYPE HTML PUBLIC "-// W3C // DTD HTML 4.01 Transitional // EN">
<html>
<head>
<title> Test page 1, create form, iframe, submit form </ title>
<meta http-equiv = "pragma" content = "no-cache">
<meta http-equiv = "cache-control" content = "no-cache">
<meta http-equiv = "expires" content = "0">
<script type = "text / javascript" src = ".. omitted / jquery.1.8.2.min.js"> </ script>
<script>
    $ (function () {// It is worth noting that the iframe will maintain the browser's history, and the browser's back / forward will change based on ifream's access history, not the main page
        $ ("# btn"). click (function () {
            var value = $ ("# pic"). val ();
            if (Utils.isEmpty (value)) {
                alert ("Please select a file");
                return false;
            }
            if (! value.match (/. jpg | .jpeg | .gif | .png | .bmp / i)) {
                alert ("File format error");
                return false;
            }
            $ ("# form0"). submit ();
        });
    });
</ script>
</ head>
<body>
    <form id = "form0" method = "post" action = ".. omitted / uploadOrgPic.html"
        enctype = "multipart / form-data" target = "hiddenFrame">
        Upload avatar: <input type = "file" name = "imageVo.image" id = "pic" /> <input
            type = "button" value = "submit" id = "btn" />
    </ form>
    <div id = "result"> </ div>
    <iframe src = "about: bland;" id = "hiddenFrame" name = "hiddenFrame"
        style = "display: none;" frameborder = "0"> </ iframe>
</ body>
</ html>



Test2.jsp: Jump to the page after background processing is completed (the background processing code is not posted here, I believe everyone will upload the file)


<% @ page language = "java" import = "java.util. *" pageEncoding = "utf-8"%> <! DOCTYPE HTML PUBLIC "-// W3C // DTD HTML 4.01 Transitional // EN">
<html>
<head>
<title> Test page 2, process results, return to parent page </ title>
<meta http-equiv = "pragma" content = "no-cache">
<meta http-equiv = "cache-control" content = "no-cache">
<meta http-equiv = "expires" content = "0">
<script>
     window.onload = function () {// Check if the parent window exists
         if (window.parent! = window) {
             var resultDiv = window.parent.document.getElementById ("result");
             resultDiv.innerHTML = 'Since it's a test, it's easy to say this sentence';
         }
     }
</ script>
</ head>
<body>
</ body>
</ html>




Method 2: $ .ajax ((..))
It is worth noting: serialize () can create URL-encoded text strings by serializing form values, but does not support file upload forms


<script>
    $ .ajax ({
        url: the url link you want to request, // default is the current page url
        aysnc: true, // whether asynchronous, default true
        cache: true, // Use cache, default true
        type: "POST", // Request method, default Get
        dataType: 'JSON', // The type of data expected by the server (if you do not specify jquery, it will be judged based on the HTTP packet MIME information)
        headers: {
            'ClientCallMode': 'ajax'
        }, // Add header, also can be added by beforeSend function
        data: $ ('# formid'). serialize (), // The data to be sent will be automatically converted to the request string format. Here is the string generated after the form is serialized
        success: function (data) {// Callback function executed successfully
            alert ("success");
        },
        error: function (request) {// Callback function that executes the error (contains three parameters: XMLHttrRequest, error information, caught exception object)
            alert ("error");
        }
    });
</ script>




Method 3: Use the jQuery plugin ajaxFileUpload.js. This method does not require a form when submitting, and cannot submit the form. It is only used for file upload.
If you need to pass other parameters at the same time as uploading the file, you can do so by setting the data property; but if you need too many parameters, this method is not recommended. Individuals prefer the method 4.


<script>
     $ ("# uploadFile"). click (function () {
         var value = $ ("# imageInput"). val ();
         if (Utils.isEmpty (value)) {
             alert ("Please select a file");
             return false;
         }
         if (! value.match (/. jpg | .jpeg | .gif | .png | .bmp / i)) {
             alert ("File format error");
             return false;
         }
         $ .ajaxFileUpload ({
             url: 'url',
             secureuri: false, // whether to enable secure submission, default false
             dataType: 'JSON', // The type of data expected by the server
             fileElementId: 'imageInput', // File field id value
             data: {
                 'name': 'abc'
             }, //Other parameters         
             success: function (data, status) {
                 alert (data);
             },
             error: function (data, status, _exception) {
                 alert (_exception);
             }

         });
     });
</ script>




Method 4: jquery.form.js


<script>
    function ajaxSubmitForm () {
        var value = $ ("# pic"). val ();
        if (Utils.isEmpty (value)) {
            alert ("Please select a file first");
            return false;
        }
        if (! value.match (/. jpg | .jpeg | .gif | .png | .bmp / i)) {
            alert ("File format error");
            return false;
        }
        var option = {
            url: '.. omitted / uploadOrgPic.ac',
            type: 'POST',
            dataType: 'json',
            headers: {
                "ClientCallMode": "ajax"
            }, // Add request header
            success: function (data) {
                alert (JSON.stringify (data));
            },
            error: function (data) {
                alert (JSON.stringify (data) + "--upload failed, please refresh and try again");
            }
        };
        $ ("# form0"). ajaxSubmit (option);
        return false; // It is best to return false, because if the button type is submit, the form will submit itself again; returning false prevents the form from being submitted again
    }
</ script>


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.