麻烦在jsp中使用简单的ajax - 内容填充然后消失

时间:2012-05-14 11:56:34

标签: javascript ajax jsp

我正在使用一个简单的jsp来填充下拉框(地址作为选项),基于输入参数(postcode)在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');
    }
    }
    }

2 个答案:

答案 0 :(得分:1)

您正在onclick提交按钮的<input type="image">发送ajax请求。但是,当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。确保您正在阅读最新资源。这可能是一个很好的起点:How to use Servlets and Ajax?

答案 1 :(得分: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>