Ajax Submission Form, AJAX implementation file upload

Source: Internet
Author: User

Ajax Submission Form, AJAX implementation file upload, the need for friends can refer to the next.

Method 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

Mode two: Use jquery's $.ajax ({..}) To support the submission of a normal form, but not the complex form containing the file; ($.post or $.get are $.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 common Ajax request, the fourth type to solve the file upload/form submission; Not much, 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" > 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=". Omit/jquery.1.8.2.min.js "></script><script>$ (function () {///Note that the IFRAME maintains the browser's history, the browser's back/ The advance will vary according to Ifream's access history, not the home page $ ("#btn"). Click (function () {var value = $ ("#pic"). Val (); if (Utils.isempty (value)) {alert (" Please select the 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= "... Omit/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>    

TEST2.JSP: Background processing After the completion of the jump page (background processing code is not posted here, upload the file I believe everyone will)

<%@ 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 () {                  if (window.parent! = window) {           //checks for the existence of a parent window                        var resultdiv= Window.parent.document.getElementById ("result");                        resultdiv.innerhtml = ' because it is a test, so simply come to this sentence ';                  }             }    </script>  </head>    <body>    </body></html>  


Way two: $. Ajax ({...})

It is worth noting that serialize () can create URL-encoded text strings by serializing form values, but does not support file upload forms

    $. Ajax ({            URL: URL link you want to request,      //defaults to the current page URL                  aysnc:true,//                async, Default True            cache:true,               //use cache, Default true            type: "POST",              //Request mode, default get            dataType: ' JSON ',           //expected server returned data type ( If you do not specify jquery will be judged according to the HTTP Packet mime information)            headers:{' clientcallmode ': ' Ajax '},//Add header, also can be added through the Beforesend function            data:$ (' #formid '). Serialize (),    //data to be sent is automatically converted to the request string format. Here is the form serialized after the generated string            success:function (data) {  //executes a successful callback function                alert ("Success");            },            Error:function (Request) {//Execute Error callback function (contains three parameters: Xmlhttrrequest, error message, caught exception object)                alert ("Error");}                                ); 

Method Three: Using the jquery plugin ajaxfileupload.js, this method is submitted without a form, and can not submit the form, only for file upload

If the file upload also to pass other parameters, by setting the Data property can be implemented, but if the need for too many parameters, it is not recommended to use this way, personal more inclined to the way four

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >Head> <title>Ajaxfileupload Uploading files </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=". Omit/jquery.js "></script><script type=" Text/javascript "src=". Omit/ajaxfileupload.js "></script><script>$ (" #uploadFile "). Click (function () {var value = $ (" # Imageinput "). Val (), if (Utils.isempty (value)) {alert (" Please select File "); return false;} if (!value.match (/.jpg|. Jpeg|. Gif|. Png|. bmp/i) {alert ("File format error"); return false;} $.ajaxfileupload ({url: ' url ', secureuri:false,//Whether secure commit is enabled, default false DataType: ' JSON ', Expected server returned data type Fileelementid: ' Imageinput ',//file domain ID value data:{' name ': ' ABC '},//other parameters Success:function (data,status) {alert (data);}, Error:function (data,status,_exception) {alert (_exception);} });}); </script> </head> <body> name: <input type= "text" name= "name"/><br/> upload avatar: <input Type= "File" id= "Imageinput" name= "Imagevo.image"/> <input type= "button" value= "Upload" id= "UploadFile"/> </ body></html>    


Mode four: Jquery.form.js

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" ><Html> <Head><title>ajax upload avatar </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=" Jquery.1.8.2.min.js "></script> <script type=" Text/javascript "src=" Jquery.form.js " ></script> Form--<form id= "FORM0" method= "POST" action= "" enctype= "multipart/form-Data "> Name: <input type=" text "name=" Userinfo.username "autocomplete=" Off "/> Avatar: <inp UT type= "file" Name= "Imagevo.image" id= "pic"/> <input type= "button" value= "Submit" onclick= "ajaxsubmitform (); " /> </form> </body> <script> function Ajaxsubmitform () {var value = $ ("#pic"). Val (); if (utils.ise Mpty (value) {Alert ("Please select File First"); return false;} if (!value.match (/.jpg|). Jpeg|. Gif|. Png|. bmp/i) {alert ("File format error"); return false;} var option = {url: '. Omit/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 retry") ; } }; $ ("#form0"). Ajaxsubmit (option); return false; It is a good idea to return false, because if the button type is submit, the form will be submitted again once; false to prevent the form from being submitted again} </script></html>   

Ajax Submission Form, AJAX implementation file upload

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.