同步处理servlet传递json数据到jsp

在servlet里面也可以用request.setAttribute传递json的数据,但是传递之前需要先将这个数据格式转化为字符串

  String jsonstr=json.toString();

            request.setAttribute("jsonstr", jsonstr);
            request.getRequestDispatcher("/showjson.jsp").forward(request, response);

前段接受可以使用jsp的参数接收,也可以使用Ajax接收方法现在先分享第一种

  <script type="text/javascript">


    
    var jsonstr = '<%=request.getAttribute("jsonstr")%>'
    jsonstr = jsonstr.replace(/[\r|\n|\t]/g,"")
   var json=JSON.parse(jsonstr)

    document.write(json.result.name+"<br/>" )
    document.write(json.result.college+"<br/>" )
    document.write(json.result.polit_status+"<br/>" )
     for(var i=0;i<json.result.proj_exp_objs.length;i++){
       for(var j in json.result.proj_exp_objs[i]){
         document.write(json.result.proj_exp_objs[i][j]+ "<br/>")
       }
     }
    var salary=json.eval.salary;
    document.getElementById("test").value = salary;


  </script>

 

后段传递的数据是string类型的所以需要用到Json.parse()方法将字符串转化为json,数据流里面有换行符或者/r所以需要将这些特殊字符先去掉,使用replace()方法,否则可能会报错

posted @ 2023-05-16 10:02  cojames  阅读(73)  评论(0)    收藏  举报