Ajax之json返回结果是集合的处理

Jquery实现ajax:

$.ajax({
      type    //数据的提交方式:get和post
       url   //数据的提交路径
       async   //是否支持异步刷新,默认是true
       data    //需要提交的数据
       datatype   //服务器返回数据的类型,例如xml,String,Json等
       success    //请求成功后的回调函数
       error   //请求失败后的回调函数});
}
)

json对服务器返回结果是集合的处理

<script>
       $(function(){
          $("#btn").click(function(){    单击按钮时
          $.ajax({
                type:"get",    请求方式
                url:"ShowServlet",    跳转路径
             async:true,    异步请求

             success:function(data){成功处理
            var json = eval('('+data+')'); 将JSON的字符串解析成JSON数据格式  
            var table="<table>";
            for(var i in json){
 table+="<tr><td>"+json[0].id+"</td><td>"+json[i].name+"</td><td>"+json[i].birthday+"</td><td>"+json[i].regTime+"</td></tr>";
            $("#show").html(table);显示在页面
             }
            table+="</table>";
            },  

代码实现:

userList.jsp

<%--
  Description:ajax 返回集合
  User: jiatp
  Date: 2019/5/22
  Time: 21:45
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
    //初始化
    $(function () {
            $("#btn").click(function () {
              $.ajax({
                  type:"post",
                  url:"showAllUserList",
                  data:{},
                  datatype:"json",
                  success:function (data) {
                      //转换为javascript对象
                      var user = eval('('+data+')');
                      var str = "<table>";
                      var strcontent = "";
                      for(var i=0;i<user.length;i++){
                          strcontent+="<tr><td>"+user[i].id+"</td><td>"+user[i].name+"</td><td>"+user[i].address+"</td></tr>"
                      }
                      str+=strcontent+"</table>";
                      $("#content").html(str);
                  },error:function () {
                   alert("error!");
                  }
              })
            })
    })
</script>
<body>
<input type="button" id="btn" value="显示集合">
<div id="content"></div>
</body>
</html>

showAllUserList.java

package com.chinasofti.servlet;

import com.chinasofti.entity.User;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Description:ajax返回一个集合对象
 * USER:jiatp
 * Date:2019/5/22 22:16
 * */
@WebServlet("/showAllUserList")
public class showAllUserList extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");

        List<User> userList = new ArrayList();

        User user1 = new User();
        user1.setName("张三");
        user1.setAddress("北京");
        user1.setId(1);
        User user2 = new User();
        user2.setName("李四");
        user2.setAddress("上海");
        user2.setId(2);
        //添加到集合
        userList.add(user1);
        userList.add(user2);
        PrintWriter out = response.getWriter();
        //将user对象转换成json格式
        JSONArray json = JSONArray.fromObject(userList);
        System.out.println(json);
        out.print(json);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}

注:var json = eval('('+data+')'); 将JSON的字符串解析成JSON数据格式

原文地址:https://www.cnblogs.com/jatpeo/p/11767542.html