gpt4 book ai didi

java - 如何知道表单提交是否成功?

转载 作者:行者123 更新时间:2023-11-29 06:13:46 27 4
gpt4 key购买 nike

我有一个表格,基本上是上传一个文件。我提交了两次表单,第一次没有多部分,第二次有多部分。

<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 部分。我在哪里确定它是否是多部分的。如果不将 resultType 存储到 session 变量,则返回 submitted,

Now I want to check for this "submitted" or similar and go for submitting the form 2nd time.

第二个表单提交:在这里我将再次检查它是否是多部分的,并检查 session 变量并进行 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函数,用于两次提交表单,寻找micoxUpload()函数

/* 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>

关于java - 如何知道表单提交是否成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5854753/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com