在 jsp 中使用简单 ajax 时出现问题 - 内容填充然后消失

Trouble using simple ajax in jsp - contents populating and then disappearing

本文关键字:问题 填充 消失 然后 jsp 简单 ajax      更新时间:2023-09-26

我正在使用一个简单的jsp来填充一个下拉框(地址作为选项),基于javascript中的ajax输入参数(邮政编码)。javascript 代码能够提取所需的数据,并在 select 元素中设置选项,但就在几分之一秒之后,所有更改都消失了,jsp 回到了它的初始状态。你能帮我解决这种行为的原因吗?提前谢谢。

主要的JSP代码:testajx.jsp

    <form name="testform" method="POST" action="testajx.jsp" >
    <h1><%=a%> testing <b>Postcode Lookup</b></h1>
    <br>
    <br>
    <input type="text" name="ziporpostalcode" size="10" maxlength="7" value="<%=ziporpostalcode%>"/>
    <input type="text" name="ziporpostalcodetest" size="10" maxlength="7" value=""/>
    <input type="hidden" name="searchPostCodeHidden" value="">
    <input type="button" name="searchPostCode" value="Search" onclick="if(ziporpostalcode.value == ''){alert('enter postcode');}else {searchPostCodeHidden.value = 'TRUE'; this.form.submit();}">
    <input type="hidden" name="searchAddressHidden" value="">
    <input type="button" name="test" value="test" onclick="alert(userAddress.value);alert('<%=userAddress%>');">
    <input type=image name="op_xxx" value="Search Address xxx" src="'jsp'htdocs'assets'images2011'buttons'search_address.gif" alt="Search Address"         onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />
    <select name="userAddress" value="<%=userAddress%>" onchange="searchAddressHidden.value =         userAddress.value; form.submit();">
        <option>--- Select ---</option>
        <%=addressOptions%>
    </select>
    <div id="ajax_res">a</div>
        </body>
    </form>

从testajax收到的结果.jsp:

    <body>
    <select name="userAddress">
        <option>--- Select ---</option>
    <%
    String addressOptions = new String();
    Picklist pl = new Picklist();
    addressOptions = "";
    String ziporpostalcode = request.getParameter("ziporpostalcode");
    pl = PostcodeHandler.getAddressList(ziporpostalcode);
    PicklistItem[] pli = pl.getItems();
    //Iterator li = sAddressList.values().iterator();
    for(int i=0; i<pl.getTotal(); i++)
        {
    addressOptions += "<option label='""+pli[i].getPartialAddress()+"'" value='""+pli[i].getMoniker()+"'">"+pli[i].getText()+"</option>";
    session.setAttribute("addressOptions", addressOptions);
    request.setAttribute("ziporpostalcode", ziporpostalcode);
    request.setAttribute("searchPostCodeHidden", ziporpostalcode);
    // addressOptions += "<option label='"+sAddressList.get(i).toString()+"'         value='"+sAddressList.get(i).toString()+"'>"+sAddressList.get(i).toString()+"</option>";
        }
    String str="This is JSP string loading from JSP page in ajax, loading time :";
    out.print(addressOptions);
    %>
    </select>


Ajax JavaScript代码是:

    <script language="Javascript" type="text/javascript">
    function createRequestObject(){
    var req; 
    try {
    // Firefox, Opera, Safari
    req = new XMLHttpRequest();
    } catch (e) {
    // Internet Explorer
    try {
    //For IE 6
    req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try {
    //For IE 5
    req = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
    alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
    }
    }
    }
    return req;
    }
    //Make the XMLHttpRequest Object
    var http = createRequestObject();
    function sendRequest(method, url){
    if(method == 'get' || method == 'GET'){
    http.open(method,url,true); 
    http.onreadystatechange = handleResponse;
    http.send(null);
    }
    }
    function handleResponse(){
    if(http.readyState == 4 && http.status == 200){
    var response = http.responseText;
    if(response){
    document.getElementById("ajax_res").innerHTML = response;
    document.getElementById("ziporpostalcodetest").value = 'response';
    document.getElementById("testform").action = 'testajax.jsp';
    alert('received something from Ajax');
    }
    }
    }

您正在<input type="image">提交按钮的onclick发送 ajax 请求。但是,在onclick完成时,您不会阻止按钮的默认行为。按钮的默认行为是提交它所在的表单。您需要通过在onclick中返回false来阻止按钮的默认行为。

所以,改变

<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />

<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value); return false;"href="#" />

具体问题无关,你对这一切有严重的设计问题。我不确定你在哪里学习HTML,JSP和Ajax,但这一切看起来都很90年代。确保您正在阅读最新的资源。这可能是一个很好的起点:如何使用 Servlet 和 Ajax?

只是厌倦了在代码中搜索错误。这是我的(不要包含jQuery核心):

<div id="content"></div>
<script type="text/javascript">
    function updateDivContent() {
        var result = jQuery.ajax({
            url: "your url",
            type: "POST",
            async: true,
            cache: false,
            data: // your form data, can use serialize from jquery
        });
        jQuery("div#content").html(result.responseText)
    }
</script>