在表单提交后显示消息的方法

approach for displaying message after form submit

本文关键字:方法 消息 显示 表单提交      更新时间:2024-03-19

我有一个包含名称、电子邮件、消息和captcha字段的表单。

我可以提交表单,并可以在服务器端验证captcha。如果一切正常,我必须使用requestDispatcher显示一个jsp。如果captcha正确,一切都很好,但如果它不正确,我会将用户重定向到显示表单的同一页面,以便用户可以重新输入captcha。但这种方法的主要问题是表单被清除,这意味着用户必须再次填充整个表单。我该如何避免这种情况,这样用户就不需要重新填写表格了。

他们还有其他更好的方法吗。

Iv'e已经尝试过进行ajax调用来验证captcha,但这种方法遇到了一些问题。无法在jquery ajax回调函数中提交表单

您可以这样做,在某个div上调用click事件,比如"submit",然后调用ajax调用并获得结果。根据结果,您可以决定是否提交表格。

提交是DIVprintCoupon是形式

$("#submit").click(function(){
        var response = '';
        $.ajax({ type: "GET",   
                 url: "ajaxprintcoupon",   
                 async: false,
                 success : function(text)
                 {
                     response = text;
                 }
        });
        alert(response);
        if(response == 'Testing'){
            $('#printCoupon').submit();
        }else{
            // no change
        }
    }); 

您必须在JS代码中使用XmlHTTPRequest。

你可以为得到答案指定回调,并根据自己的意愿进行处理。在我的案例中,我从服务器获取要输出的代码,具有ALL INPUTS的Form保持在以前的条件下,html页面上唯一的div"output"被修改。

以下是我的程序的一个简短示例:页面的html

<script type="text/javascript" src="./js/script.js">/script>
<form name="someForm">
<p><b>Enter your text here:</b></p>`
<p><textarea rows="10" cols="45" name="code"></textarea></p>
<input type="button" value="Send it" onclick="sendIt()"/>
</form> </code>
<div id="output"></div> 

在我的情况下,script.js只更新页面的一部分

function sendIt() {
    var theCode = document.codeHolderForm.code.value;
    var linkToDiv = document.getElementById("output");
    linkToDiv.innerHTML = 'p> Server response below: p>';
    var request = getXmlHttp();
    request.open("POST", "/", true);
    request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    request.onreadystatechange = function () {
        if (request.readyState != 4) return;
        if (request.status == 200) {
            linkToDiv.innerHTML += 'p>' + request.responseText + '/p>';
        } else {
            handleError(request.statusText);
        }
    };
    request.send("code=" + theCode);
}
function handleError(message) {
    alert("Error: "+message)
}
function getXmlHttp() {
    var xmlhttp;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}