本文介绍了我如何知道表单提交是否成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,基本上是要上传一个文件。

 <输入类型=按钮tabindex我输入了两次表格,1没有多部分, =5value =Createid =btnSclass =btnonClick =submitForm(this.form,'/ test / upload'); return false; /> 


//第一次提交
form.setAttribute(action,url_action);
form.setAttribute(method,post);
form.submit();

//第二次提交
form.setAttribute(action,url_action);
form.setAttribute(method,post);
form.setAttribute(enctype,multipart / form-data);
form.setAttribute(encoding,multipart / form-data);
form.submit();

但是我想先检查第一个表单提交是否成功,然后转到第二个子表单 p>

在引用@Vern之后进行编辑

$ p $ var postString = getPostString();
var client = new XMLHttpRequest();
client.onreadystatechange = handler(form,url_action);
client.open(POST,url_action,true);
client.setRequestHeader(Content-type,application / x-www-form-urlencoded);
client.setRequestHeader(Content-length,postString.length);
client.setRequestHeader(Connection,close);
client.send(postString);

函数处理程序(表单,url_action)
{
if(this.readyState == 4&& this.status == 200){
//这里提交的是我从servlet收到的文本如果第一次提交成功
if(xmlhttp.responseText ==submitted){
secondSend(form,url_action);
} else {
alert(Not good!);


$ b函数getPostString()
{

}
函数secondSend(form,url_action)
{
form.setAttribute(action,url_action);
form.setAttribute(method,post);
form.setAttribute(enctype,multipart / form-data);
form.setAttribute(encoding,multipart / form-data);
form.submit();
}

这是我的servlet部分。我在哪里确定它的多部分或不。如果不将 resultType 存储到会话变量中,则返回提交

第二个表单提交:在这里我将再次检查它的多部分,并检查会话变量并进行CRUD。 (这个IdentifyNow基本上是一种请求调节器)

pre $ public String identifyNow()throws ServletException,java.io.IOException
{
UploadXmlAgent uploadAgent;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

System.out.println(\\\
\\\
***************************** **** \\\
isMultipart:+ isMultipart);

if(isMultipart)
{
session = request.getSession(false);

System.out.println(\\\
This is multipart and isNew+ session.isNew());
if(session!= null)
{
System.out.println(\\\
inside session);
requestType = session.getAttribute(resultType)。toString();
//基于requestType识别,实例化适当的Handler
//session.invalidate();
if(requestType.equals(Create))
{
uploadAgent = new UploadXmlAgent(realPath,request,paramMap);
uploadAgent.retrieveXml();
return uploadAgent.uploadXml();
}
else if(requestType.equals(Update))
{

}
else if(requestType.equals(Delete) )
{

}
}
else
{
returnSession is null;
}

}
else
{
System.out.println(\\\
Not a multipart);
paramMap = request.getParameterMap();
if(paramMap == null)
抛出新的ServletException(
getParameterMap返回null:+ getClass()。getName());

iterator = paramMap.entrySet()。iterator();
System.out.println(\\\
+ paramMap.size());
while(iterator.hasNext())
{
Map.Entry me =(Map.Entry)iterator.next();
if(me.getKey()。equals(resultType))
{
String [] arr =(String [])me.getValue();
requestType = arr [0];
System.out.println(Inside returntype:+ requestType);
}
}
session = request.getSession(true);
session.setAttribute(returntype,requestType);
System.out.println(Session.isNew =+ session.isNew());
返回提交;
}
返回noCreate;
}

这里是Javascript函数,用于提交表单两次,查找 micoxUpload()函数

  / *标准小函数* / 
函数$ m(quem ){
return document.getElementById(quem)
}
function remove(quem){
quem.parentNode.removeChild(quem);
}
function addEvent(obj,evType,fn){
// elcio.com.br/crossbrowser
if(obj.addEventListener)
obj.addEventListener( evType,fn,true)
if(obj.attachEvent)
obj.attachEvent(on+ evType,fn)
}
函数removeEvent(obj,type,fn) {
if(obj.detachEvent){
obj.detachEvent('on'+ type,fn);
} else {
obj.removeEventListener(type,fn,false); }
}
/ *上传功能* /
函数micoxUpload(form,url_action,id_element,html_show_loading,html_error_http){

/ ******
* micoxUpload - 将表单提交给隐藏的iframe。可以用来上传
*使用但不删除我的名字。创作共用。
*Versão:1.0 - 03/03/2007 - 测试无FF2.0 IE6.0 e OP9.1
*作者:Micox - NáironJCG - elmicoxcodes.blogspot.com - [email protected] .br
*参数:
*表单 - 要提交的表单或ID
* url_action - 要提交表单的网址。像形式的动作参数。
* id_element - 将会收到上传返回的元素。
* html_show_loading - 将在加载
时显示的文本(或图像)* html_error_http - 将显示HTTP错误的文本(或图像)。
******* /

//测试'form'是一个html对象还是一个id字符串
form = typeof(form)==string ?$ M(形式):表

var erro =;
if(form == null || typeof(form)==undefined){erro + =第一个参数的形式不存在.\\\
;}
else if(form .nodeName.toLowerCase()!=form){erro + =第一个参数的形式它不是一个form.\\\
;}
if($ m(id_element)== null){erro如果(erro.length> 0){
alert(Error in call micoxUpload:\\\
+ erro))+ =第三个参数的元素不存在。 ;
return;
}


//创建iframe
var iframe = document.createElement(iframe);
iframe.setAttribute(id,micox-temp);
iframe.setAttribute(name,micox-temp);
iframe.setAttribute(width,0);
iframe.setAttribute(height,0);
iframe.setAttribute(border,0);
iframe.setAttribute(style,width:0; height:0; border:none;);

//添加到文档
form.parentNode.appendChild(iframe);
window.frames ['micox-temp']。name =micox-temp; // ie吸

//添加事件
var carregou = function(){
removeEvent($ m('micox-temp'),load,carregou);
var cross =javascript:;
cross + =window.parent。$ m('+ id_element +').innerHTML = document.body.innerHTML; void(0);;

$ m(id_element).innerHTML = html_error_http;
$ m('micox-temp')。src = cross;
// del iframe
setTimeout(function(){remove($ m('micox-temp'))},250);
addEvent($ m('micox-temp'),load,carregou)

//表单的属性
/*form.setAttribute( 目标, micox-TEMP);
form.setAttribute(action,url_action);
form.setAttribute(method,post); * /
//form.submit();


var postString = getPostString();
var client;
if(window.XMLHttpRequest){// IE7 +,Firefox,Chrome,Opera,Safari
client = new XMLHttpRequest();
} else {// IE6,IE5
client = new ActiveXObject(Microsoft.XMLHTTP);
}

//client.onreadystatechange=handler(form,url_action);
client.open(POST,url_action,true);
client.setRequestHeader(Content-type,application / x-www-form-urlencoded);
client.setRequestHeader(Content-length,postString.length);
client.setRequestHeader(Connection,close);
client.onreadystatechange = function(){

if(client.readyState == 4&& client.status == 200){
alert(client.responseText) ; //这会从servlet返回我的文本
secondSend(form,url_action);
}
};
client.send($ postStr);

alert(第一次请求发送);
// secondSend(form,url_action);

//加载
if(html_show_loading.length> 0){
$ m(id_element).innerHTML = html_show_loading;
}
函数getPostString()
{
$ postStr = document.getElementsByTagName(confname);
$ postStr + = document.getElementsByTagName(returntype);
返回$ postStr;

函数secondSend(form,url_action)
{

form.setAttribute(target,micox-temp);
form.setAttribute(action,url_action);
form.setAttribute(method,post);
form.setAttribute(enctype,multipart / form-data);
form.setAttribute(encoding,multipart / form-data);
form.submit();
if(html_show_loading.length> 0){
$ m(id_element).innerHTML = html_show_loading;




解决方案

submit()没有返回值,因此您无法根据上面的代码检查提交结果。



然而, ,常见的做法是使用Ajax并使用函数来设置标志。这样,您可以检查表单是否成功提交。更不用说,通过服务器回复,您可以进一步验证表单是否已正确传输到服务器:)



希望它有帮助。干杯!






下面的代码应该给你一个如何去做的想法:

 函数first_send(){
//局部变量
var xmlhttp;

//创建对象
if(window.XMLHttpRequest){// IE7 +,Firefox,Chrome,Opera,Safari
xmlhttp = new XMLHttpRequest();
} else {// IE6,IE5
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);


//设置函数
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4&& xmlhttp.status == 200){
//(1)如果请求成功,检查服务器的回复
//收到
//(2)设置标志/启动下一个函数发送
//示例
if(xmlhttp.responseText ==ReceiveSuccess){
secondSend();
} else {
//错误处理在这里
}
}
}

//获取你想要的第一组数据发送
var postString = getPostString();

//发送
xmlhttp.open(POST,form1.php,true);
xmlhttp.setRequestHeader(Content-type,application / x-www-form-urlencoded);
xmlhttp.setRequestHeader(Content-length,postString.length);
xmlhttp.setRequestHeader(Connection,close);
xmlhttp.send(postString);
}

您需要:

  function getPostString(){
//从表单中收集数据
}

函数secondSend(){
//你可以创建这个函数并且像
之类的文章一样发布,或者直接发送,就像你的代码一样直接发送

希望它有帮助(:






这段代码应该做的诀窍,但一定要填写您使用的HTML表单!另外,如果您需要,请将第一个表单提交到提交中:

 < script type =text / javascript> 
var postString = getPostString();
var client = new XMLHttpRequest(); //您不应该创建它

//打开连接并设置必要的
client.open(POST,url_action,true);
client.setRequestHeader(Content-type, application / x-www-form-urlencoded);
client.setRequestHe ader(Content-length,postString.length);
client.setRequestHeader(Connection,close);

//创建函数
client.onreadystatechange = function(){
if(xmlhttp.readyState == 4&& xmlhttp.status == 200){
if(xmlhttp.responseText ==Success){
secondSend();
} else {
alert('In Error');
}
}
};

client.send(postString);

函数getPostString()
{
//从您的表单中获取您的postString数据

//返回您的数据以发布
返回$ postStr;
}

函数secondSend()
{
//请确保在发布

form.setAttribute( 行动,url_action);
form.setAttribute(method,post);
form.setAttribute(enctype,multipart / form-data);
form.setAttribute(encoding,multipart / form-data);
form.submit();
}
< / script>


I have a form, basically to upload a file. I am submitting the form twice, 1 without multipart and the 2nd 1 with multipart.

<input  type="button"  tabindex="5"  value="Create" id="btnS" class="btn" onClick="submitForm(this.form,'/test/upload'); return false;" />


//1st submission
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.submit();

//2nd submission
form.setAttribute("action",url_action);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
form.submit();

but instead I want to 1st check if the 1st form submission is successful then go for 2nd submition

Edited after referring @Vern

var postString = getPostString();
var client=new XMLHttpRequest();
client.onreadystatechange=handler(form,url_action);
client.open("POST",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.setRequestHeader("Content-length", postString.length);
client.setRequestHeader("Connection", "close");
client.send(postString);

function handler(form,url_action)
 {
     if(this.readyState == 4 && this.status == 200) {
//Here submitted is the text that I receive from the servlet If 1st submit is successful
         if (xmlhttp.responseText == "submitted"){
             secondSend(form,url_action);
            } else {
                alert("Not good!");
            }
         }
 }
 function getPostString()
 {

 }
 function secondSend(form,url_action)
 {
 form.setAttribute("action",url_action);
 form.setAttribute("method","post");
 form.setAttribute("enctype","multipart/form-data");
 form.setAttribute("encoding","multipart/form-data");
 form.submit();
 }

Here is my servlet part. where I am identifying if its multipart or not. If not store the resultType to a session variable then return submitted,

2nd Form submission: Here I will check if its multipart again, and check the session variable and go for CRUD. (This IdentifyNow is basically a kind of request modulator)

public String identifyNow()throws ServletException, java.io.IOException
{
    UploadXmlAgent uploadAgent;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    System.out.println("\n\n*********************************\nisMultipart: "+isMultipart);

    if(isMultipart)
    {
        session=request.getSession(false);

        System.out.println("\nThis is multipart and isNew"+session.isNew());
        if(session!=null)
        {
            System.out.println("\ninside session");
            requestType=session.getAttribute("resultType").toString();
            //Identified based on requestType, instantiate appropriate Handler
            //session.invalidate();
            if(requestType.equals("Create"))
            {
                uploadAgent=new UploadXmlAgent(realPath,request,paramMap);
                uploadAgent.retrieveXml();
                return uploadAgent.uploadXml();
            }
            else if(requestType.equals("Update"))
            {

            }
            else if(requestType.equals("Delete"))
            {

            }
        }
        else
        {
            return "Session is null";
        }

    }
    else
    {
        System.out.println("\nNot a multipart");
        paramMap=request.getParameterMap();
        if (paramMap == null)
            throw new ServletException(
              "getParameterMap returned null in: " + getClass().getName());

        iterator=paramMap.entrySet().iterator();
        System.out.println("\n"+paramMap.size());
        while(iterator.hasNext())
        {
            Map.Entry me=(Map.Entry)iterator.next();
            if(me.getKey().equals("resultType"))
            {
                String[] arr=(String[])me.getValue();
                requestType=arr[0];
                System.out.println("Inside returntype: "+requestType);
            }
        }
        session=request.getSession(true);
        session.setAttribute("returntype", requestType);
        System.out.println("Session.isNew="+session.isNew());
        return "submitted";
    }
    return "noCreate";
}

Here is Javascript function which is used to submit form twice, look for micoxUpload() function.

/* standard small functions */
   function $m(quem){
 return document.getElementById(quem)
}
function remove(quem){
 quem.parentNode.removeChild(quem);
}
function addEvent(obj, evType, fn){
 // elcio.com.br/crossbrowser
    if (obj.addEventListener)
    obj.addEventListener(evType, fn, true)
if (obj.attachEvent)
    obj.attachEvent("on"+evType, fn)
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, fn );
  } else {
    obj.removeEventListener( type, fn, false ); }
}
/* THE UPLOAD FUNCTION */
function micoxUpload(form,url_action,id_element,html_show_loading,html_error_http){

    /******
* micoxUpload - Submit a form to hidden iframe. Can be used to upload
* Use but dont remove my name. Creative Commons.
* Versão: 1.0 - 03/03/2007 - Tested no FF2.0 IE6.0 e OP9.1
* Author: Micox - Náiron JCG - elmicoxcodes.blogspot.com - [email protected]
* Parametros:
* form - the form to submit or the ID
* url_action - url to submit the form. like action parameter of forms.
* id_element - element that will receive return of upload.
* html_show_loading - Text (or image) that will be show while loading
* html_error_http - Text (or image) that will be show if HTTP error.
*******/

 //testing if 'form' is a html object or a id string
 form = typeof(form)=="string"?$m(form):form;

 var erro="";
 if(form==null || typeof(form)=="undefined"){ erro += "The form of 1st parameter does       not exists.\n";}
 else if(form.nodeName.toLowerCase()!="form"){ erro += "The form of 1st parameter its not a form.\n";}
 if($m(id_element)==null){ erro += "The element of 3rd parameter does not exists.\n";}
 if(erro.length>0) {
  alert("Error in call micoxUpload:\n" + erro);
  return;
 }


 //creating the iframe
 var iframe = document.createElement("iframe");
 iframe.setAttribute("id","micox-temp");
 iframe.setAttribute("name","micox-temp");
 iframe.setAttribute("width","0");
 iframe.setAttribute("height","0");
 iframe.setAttribute("border","0");
 iframe.setAttribute("style","width: 0; height: 0; border: none;");

 //add to document
 form.parentNode.appendChild(iframe);
 window.frames['micox-temp'].name="micox-temp"; //ie sucks

 //add event
   var carregou = function() {
   removeEvent( $m('micox-temp'),"load", carregou);
   var cross = "javascript: ";
   cross += "window.parent.$m('" + id_element + "').innerHTML = document.body.innerHTML; void(0); ";

   $m(id_element).innerHTML = html_error_http;
   $m('micox-temp').src = cross;
   //del the iframe
   setTimeout(function(){ remove($m('micox-temp'))}, 250);
  }
 addEvent( $m('micox-temp'),"load", carregou)

 //properties of form
 /*form.setAttribute("target","micox-temp");
 form.setAttribute("action",url_action);
 form.setAttribute("method","post");*/
 //form.submit();


 var postString = getPostString();
 var client;
 if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
 client=new XMLHttpRequest();
 } else {                    // IE6, IE5
 client=new ActiveXObject("Microsoft.XMLHTTP");
 }

 //client.onreadystatechange=handler(form,url_action);
 client.open("POST",url_action,true);
 client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 client.setRequestHeader("Content-length", postString.length);
 client.setRequestHeader("Connection", "close");
 client.onreadystatechange   =   function(){

 if (client.readyState==4 && client.status==200){
     alert(client.responseText); //This gives back my text from servlet
     secondSend(form,url_action);
 }
 };
 client.send($postStr);

 alert("1st request send");
 //secondSend(form,url_action);

 //while loading
 if(html_show_loading.length > 0){
  $m(id_element).innerHTML = html_show_loading;
 }
function getPostString()
 {
 $postStr=document.getElementsByTagName("confname");
 $postStr+=document.getElementsByTagName("returntype");
 return $postStr;
 }
     function secondSend(form,url_action)
 {

 form.setAttribute("target","micox-temp");
 form.setAttribute("action",url_action);
 form.setAttribute("method","post");
 form.setAttribute("enctype","multipart/form-data");
 form.setAttribute("encoding","multipart/form-data");
 form.submit();
 if(html_show_loading.length > 0){
  $m(id_element).innerHTML = html_show_loading;
 }
 }
}
解决方案

submit() does not have a return value and as such you are not able to check the outcome of the submission just based on your code above.

However, the common way to do it is actually to use Ajax and use a function to set a flag. That way, you can check if the form is successfully submitted. Not to mention, with the server reply, you can further validate if the form has been transmitted correctly to the server :)

Hope it helped. Cheers!


The following code should give you an idea of how to do it:

function first_send(){
    // Local Variable
    var xmlhttp;

        // Create Object
    if (window.XMLHttpRequest){ // IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {                    // IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

        // Set Function
    xmlhttp.onreadystatechange=function(){
      if (xmlhttp.readyState==4 && xmlhttp.status==200){
        // (1) Check reply from server if request has been successfully
        //     received
        // (2) Set flag / Fire-off next function to send
        // Example
        if (xmlhttp.responseText == "ReceiveSuccess"){
          secondSend();
        } else {
          // Error handling here
      }
      }
    }

        // Gets the first set of Data you want to send
    var postString = getPostString();

          // Send
    xmlhttp.open("POST","form1.php",true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
       xmlhttp.setRequestHeader("Content-length", postString.length);
       xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.send(postString);
}

And you'll need:

function getPostString(){
          // Collect data from your form here
}

function secondSend(){
      // You can create this function and post like above
      // or just do a direct send like your code did
}

Hope it helps (:


This code ought to do the trick, but be sure to fill up with the HTML form that you're using! Also, put the first form in a submission if you require:

<script type="text/javascript">
  var postString = getPostString();
  var client     = new XMLHttpRequest();  // You shouldn't create it this way.

            // Open Connection and set the necessary
        client.open("POST",url_action,true);
        client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        client.setRequestHeader("Content-length", postString.length);
        client.setRequestHeader("Connection", "close");

            // Create function
        client.onreadystatechange   =   function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                if (xmlhttp.responseText == "Success") {
                    secondSend();
                } else {
                    alert('In Error');
                }
            }
        };

        client.send(postString);

  function getPostString()
  {
    // Get your postString data from your form here

        // Return your Data to post
        return $postStr;
  }

  function secondSend()
  {
        // Make sure you fill up your form before you post

    form.setAttribute("action",url_action);
    form.setAttribute("method","post");
    form.setAttribute("enctype","multipart/form-data");
    form.setAttribute("encoding","multipart/form-data");
    form.submit();
  }
</script>

这篇关于我如何知道表单提交是否成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 14:51