【发布时间】:2016-12-10 08:41:33
【问题描述】:
我想修改这个 ajax 请求,使其使用接收的 JSON 填充选项卡(动态)。现在,ajax 代码只打印由 Servlet 接收的对象 json。这是jquery中的代码:
<script type="text/javascript">
var form = $('#form1');
form.submit(function () {
//event.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
var result=data;
$('#result').html(result);
// Result is a ID of a <div><div> in which I
// print the json string. I want build a
// table here. But I want that this table is dinamic,
// that is also the NAME of columns must depends from json
console.log(result);
}
});
return false;
}); </script>
相反,这是我的 servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String k = request.getParameter("choose");
//From a dropdown select, for example I choose to print
// the table "products"
if(k.equals("products")){
ArrayList<Products> list = new ArrayList<Products>();
list = bDBean.listProducs();
Iterator<Products> i = list.iterator();
while(i.hasNext()){
Products temp = i.next();
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
String json = gson.toJson(temp);
// response.setContentType("application/json");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
}
【问题讨论】:
-
你现在返回多个 json 字符串,为什么?
-
它们是我要放置在表格中的对象
-
响应如何??
-
每个对象都有这种形式 = {"productNo":1, "name":"Cheese","price":5.99}...等...
标签: javascript jquery json ajax servlets