$ each()函数不使用ajax显示来自servlet的JSON对象带来的任何数据

时间:2014-05-27 07:46:39

标签: java jquery ajax json jsp

我想在jsp页面中显示从数据库中检索到的书名。一切正常,但是当要执行ajax成功时,each函数正在解决问题。它没有显示任何内容。我检查了所有内容,在它之后,所有内容都运行良好,即使检索到数据并将其作为ajax传回JSON object,但iterating时出现问题。如果代替jquery的每个函数,我会写任何其他警报函数或简单文本来显示,它是有效但不是每个函数。问题出在哪儿? Plz帮助我。以下是我的servletjsp页面的代码。

EbookSearchResult.java

response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String search=request.getParameter("searchText");
            String pattern="%"+search+"%";
            ArrayList<String> result=new ArrayList<String>();
            try{
                Connectivity obj=new Connectivity();
                obj.connect();
                Statement stmt;
                ResultSet rs;
                stmt=obj.con.createStatement();
                rs=stmt.executeQuery("select bookTitle from ebooks where bookTitle LIKE '"+pattern+"'");
                if (!rs.next()) 
                {                
                    return;
                }          
                while(rs.next()){
                    String str=rs.getString("bookTitle");
                    result.add(str);                    
                }
                String json = new Gson().toJson(result);    
                out.write(json);                        
            }
            catch(Exception e){
                out.println(e.toString());
            }

search.jsp的

<script type="text/javascript">
$(document).ready(function()
{
$("#SearchButton").click(function()
{
var searchText = $("#search").val();
if(searchText.length > 3)
{
$("#searchResult").html("<img src='images/loading.gif'/>Checking availability...");
$.ajax({
    // the URL for the request
    url: "EbookSearchResult.do",

    // the data to send (will be converted to a query string)
    data: {
        searchText: searchText
    },

    // whether this is a POST or GET request
    type: "POST",

    // the type of data we expect back
    dataType : "json",

    // code to run if the request succeeds;
    // the response is passed to the function
    success: function(json) {        
        $.each(json, function(index,value) {               
            $("#searchResult").append(value);      
                    });
    },

    // code to run if the request fails; the raw request and
    // status codes are passed to the function
    error: function( xhr, status, errorThrown ) {
        $("#searchResult").html("No Search Results found...");
        console.log( "Error: " + errorThrown );
        console.log( "Status: " + status );
        console.dir( xhr );
    }
});
}

else
{
$("#searchResult").html("Search Text should be atleast 4 character");
}

});
});

</script>

0 个答案:

没有答案