Ajax获取返回值通过out.print()传递json数据,达到局部刷新


1,写AJax,Controller除了用return传值,还可以用JSP九大内置对象之一的out来传递。

2,Controller给Jsp使用out.print()传递数据,需要现在Controller里将数据转成json字串,在Jsp的js语句中调用时候需要将json字串转为对象。

controller

 @RequestMapping(value ="ajaxtest")
    public void ajaxtest(String towards, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");//如果不加此行,中文编码会乱码
        List list=fangyuanservice.showByTowards(towards);
        PrintWriter out = response.getWriter();
        String str = JSON.toJSONString(list);//将list转化为JSON字符串
        out.print(str);
        out.close();
    }

Jsp中AJax

    function btnfun2() {
        $.ajax({
            url: "ajaxtest",    //controller,处理数据的地址
            type: "POST", //请求方式
            data: {"towards": "南"}, //需要上传的数据
            success: function (list) {    //请求成功
                myhtmlset='';
                //例遍对象数组,同时使用成员变量内容
                $.each( JSON.parse(list), function(index, it){//JSON.parse(list)由JSON字符串转换为JSON对象
                    myhtmlset+="
\n" + "
test
\n" + "
"; }); $("#myajax").html(myhtmlset);//局部刷新 }, error: function () { alert("出错啦..."); },//表示如果请求响应出现错误,会执行的回调函数 }); }

Jsp中调用函数

朝阳