使用easyui从servlet传递json数据到前端页面的两种方法

 两种方法获取的数据在servlet层传递的方法相同,下面为Servlet中代码,以查询表中所有信息为例。

//重写doGet方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
​
  request.setCharacterEncoding(\"UTF-8\");//防止request请求时中文数据出现乱码
  String flag = request.getParameter(\"flag\");//通过flag值判定增删改查操作
  if(flag == null) {
    queryOffer(request,response);
  }else if(\"add\".equals(flag)){
    addOffer(request,response);
  }else if(\"del\".equals(flag)) {
    deleteOffer(request,response);
  }else if(\"update\".equals(flag)) {
    updateOffer(request,response);
  }
}
​
//处理从数据库查询到的数据以返回前端
protected void queryOffer(HttpServletRequest request, HttpServletResponse response) {
  // TODO Auto-generated method stub
  List<Offer> offers = new ArrayList<Offer>();
  offers = offerservice.queryOfferService();
  try {
    String str=JSONArray.toJSONString(offers);//将数据库查询到的集合转换成JSON字符串
    System.out.println(str);
    response.setContentType(\"text/html;charset=utf-8\");//防止response时中文数据乱码
    response.getWriter().print(str);//向前台传递字符串
  } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
  }
}

通过easyui包含的table标签中的属性来获取后端传递的数据

jsp代码:

url:传递数据的地址(本篇使用的是servlet,所以路径为servlet路径;也可以使用action或者php)

field:传递的JSON数据的字段名称,就是数据库的字段(列名)

<table id=\"dg\" title=\"用户列表\" class=\"easyui-datagrid\" style=\"width:80%;height:250px\"
      url=\"<%=request.getContextPath() %>/OfferServlet\"   
      toolbar=\"#toolbar\"
      rownumbers=\"true\" fitColumns=\"true\" singleSelect=\"true\">
    <thead>
      <tr>
        <th field=\"offerid\" width=\"50\">商品ID</th>
        <th field=\"offername\" width=\"100\">商品名称</th>
        <th field=\"offertype\" width=\"200\">商品类型</th>
        <th field=\"offerdesc\" width=\"200\">商品描述</th>
        <th field=\"price\" width=\"200\">商品价格</th>
      </tr>
    </thead>
  </table>

通过JS来传递JSON数据到前端

jsp代码:

<table id=\"dg\" title=\"用户列表\" class=\"easyui-datagrid\" style=\"width:1000px;height:250px\" toolbar=\"#toolbar\">
</table>

js代码:

title:显示的表格列名

$(function(){
  $(\'#dg\').datagrid({
    url:\"${pageContext.request.contextPath}/OfferServlet\",//servlet路径
    columns:[[
      {field:\'offerid\',title:\'商品ID\',width:100},
      {field:\'offername\',title:\'商品名称\',width:100},
      {field:\'offertype\',title:\'商品类型\',width:100},
      {field:\'offerdesc\',title:\'商品描述\',width:300},
      {field:\'price\',title:\'商品价格\',width:150}
    ]]   
  });
});

以上所述是小编给大家介绍的用easyui从servlet传递json数据到前端页面的两种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容