Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

Creating a json object in jsp and using it with JQuery

I've created a JSP application, which gets results based on a user search (using lucene). I store the results in a Bean.

I'm also using Jquery Ajax to display the results.

$.ajax({
    url : "search.jsp",
    data : "search=test",
    success : function(html) {
        ("#search_results").hide().html(html).fadeIn(1500);
    }
});

search.jsp

for (int i = 0; i < size; i++) {
    out.println(searchResult.get(i).getHTML());
}

This is working fine, however I want to change it so it returns a JSON object to JQuery and then let JQuery parse the objects and display the results

I am not sure how to do this as I'm new to JSON objects and JSP. I could possibly do something like

JSONObject json = new JSONObject();
json.put("title", "TITLE_TEST");
json.put("link", "LINK_TEST");

but I dont know how to return json to jquery then let jquery parse the objects

Any help is appreciated :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an example you may take a look at. Basically your JSP page might look like this:

<%@page contentType="text/html; charset=UTF-8"%>
<%@page import="org.json.simple.JSONObject"%>
<%
    JSONObject json = new JSONObject();
    json.put("title", "TITLE_TEST");
    json.put("link", "LINK_TEST");
    out.print(json);
    out.flush();
%>

and on the client:

$.ajax({
    url : 'search.jsp',
    data : { search: 'test' },
    dataType: 'json',
    success : function(json) {
        alert(json.title);
    }
});

And here are even more examples.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...