在 jsp 中创建一个 json 对象并将其与 JQuery 一起使用 [英] Creating a json object in jsp and using it with JQuery
问题描述
我创建了一个 JSP 应用程序,它根据用户搜索(使用 lucene)获取结果.我将结果存储在 Bean 中.
I've created a JSP application, which gets results based on a user search (using lucene). I store the results in a Bean.
我也在使用 Jquery Ajax 来显示结果.
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);
}
});
搜索.jsp
for (int i = 0; i < size; i++) {
out.println(searchResult.get(i).getHTML());
}
这工作正常,但是我想更改它,以便它向 JQuery 返回一个 JSON 对象,然后让 JQuery 解析对象并显示结果
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
我不知道该怎么做,因为我是 JSON 对象和 JSP 的新手.我可能会做类似
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");
但我不知道如何将 json
返回给 jquery 然后让 jquery 解析对象
but I dont know how to return json
to jquery then let jquery parse the objects
感谢任何帮助:)
推荐答案
这里是 an例子你可以看看.基本上您的 JSP 页面可能如下所示:
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();
%>
在客户端:
$.ajax({
url : 'search.jsp',
data : { search: 'test' },
dataType: 'json',
success : function(json) {
alert(json.title);
}
});
这里甚至还有更多示例.
这篇关于在 jsp 中创建一个 json 对象并将其与 JQuery 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!