Ajax 返回 json

前端之家收集整理的这篇文章主要介绍了Ajax 返回 json前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

后台java代码

public void doPost(HttpServletRequest request,HttpServletResponse response)
            throws ServletException,IOException {

        response.setContentType("text/html;charset=utf-8");
        JSONObject json = null;
        PrintWriter out = response.getWriter();
        System.out.println("load in ....");
        // 初始化数据
        class Cat{
            Cat (String name,int height ) {
                this.height = height;
                this.name = name;
            }
            int height;
            String name;
        }

        ArrayList<Cat> list = new ArrayList<Cat>();
        list.add(new Cat("Tom",20));
        list.add(new Cat("Abby",30));
        list.add(new Cat("Kitty",10));
        list.add(new Cat("Julie",40));

        // 定义返回值的容器
        StringBuffer buffer = new StringBuffer();
        // 当json返回 对象时,外面必须加一对小括号
        buffer.append("({");

        for(int i = 0; i < list.size(); i++){
            Map map = new HashedMap();
            map.put("name",list.get(i).name);
            map.put("height",list.get(i).height);
            json = JSONObject.fromObject(map);
            buffer.append(i);
            buffer.append(":");
            buffer.append(json.toString());

            if(i != list.size()-1) {
                buffer.append(",");
            }
        }

        buffer.append("})");
        out.print(buffer);

        out.flush();
        out.close();

    }

js脚本

$(function() {
    $("#verify").click(function(){
        var userName = $("#userName").val();
        $.ajax({
            type: "post",url: "servlet/ResultJSON",async: true,data : "name=" + userName,dataType: "Text",success: function(data){
                alert(data);
                var objs = eval(data);
                try{
                    for (var i = 0; i < 10; i++) {
                        var o = objs[i];
                        $("#result").append(o.name + "---" + o.height + "<br />");}
                }catch(e){
                    alert("数据往下没有了");
                }
            }
        });
    });
});
原文链接:https://www.f2er.com/ajax/163462.html

猜你在找的Ajax相关文章