我如何知道表单提交是否成功?
我有一个表格,基本上是上传一个文件。我要提交两次表格,第1次不包含多部分,第二次1次包含多部分。
<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();
但是我想先检查一下第一次提交表单是否成功,然后再进行第二次提交
引用@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();
}
这是我的servlet部分。我在哪里确定它是否由多个部分组成。如果未将 存储到会话变量中,则返回submitted
,
现在,我要检查此“已 ”或类似内容,然后第二次提交表格。
第二表单提交:在这里,我将再次检查其多部分内容,并检查会话变量并进行CRUD。(此IdentifyNow本质上是一种请求调制器)
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";
}
这是用于两次提交表单的Javascript函数,查找 。
/* 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 - micoxjcg@yahoo.com.br
* 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()没有返回值,因此,仅根据上面的代码,您将无法检查提交的结果。
但是,执行此操作的常用方法实际上是使用Ajax并使用函数来设置标志。这样,您可以检查表单是否成功提交。更不用说,随着服务器的回复,您可以进一步验证表单是否已正确传输到服务器:)
希望能有所帮助。干杯!
以下代码应使您了解如何执行此操作:
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);
}
而且您需要:
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
}
希望能帮助到你 (:
这段代码应该可以解决问题,但是请务必填写您正在使用的HTML表单!另外,如果需要,请在提交中填写第一份表格:
<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>
以上是 我如何知道表单提交是否成功? 的全部内容, 来源链接: utcz.com/qa/422027.html