0

我正在使用一个简单的 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');
    }
    }
    }

4

2 回答 2

1

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

所以,改变

<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 年代的。确保您正在阅读最新的资源。这可能是一个很好的起点:如何使用 Servlets 和 Ajax?

于 2012-05-15T03:43:12.750 回答
0

只是厌倦了在代码中搜索错误。这是我的(不要忘记包含 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>
于 2012-05-14T16:01:16.220 回答