zoukankan      html  css  js  c++  java
  • Servlet及前端JSP中的JSON简单传递

    在后台servlet中,若需要将json传至前台,可以将json字符串通过request的setAttribute方法进行传值,通过转发交接给JSP页面(其实,在tomcat等容器中,除了转换和编译阶段,servlet跟JSP区别也不是太大),测试代码如下:

    1         request.setAttribute("jsonstr", respMessage);
    2         request.getRequestDispatcher("/WEB-INF/jsp/showPhotos.jsp").forward(request, response);

    然后,在JSP中需要将其读取出来,在JavaScript中,读取方法如下:

     1  <script type="text/javascript">
     2  //{"currentUser":"zhang","success":"true","photoList":[{"id":"4545","createUser":"sere","modifyUser":"zhang","dr":"0"}]}
     3         
     4  //上面的是我后台传过去的json,下面是JavaScript的解析方法
     5      var jsonstr = '<%=request.getAttribute("jsonstr")%>';
     6      var obj = eval('(' + jsonstr + ')');
     7      //json中的属性
     8     alert(obj.success);
     9            
    10     //json中的list
    11     alert(obj.photoList[0].id);
    12  </script>

     使用这个方法的话,需要注意:request是jsp中的内置对象,若js是单独文件,可能会出现取值为null的情况,可以在jsp中设置一个隐藏域,然后通过getElemetById之类的方法调用其中的value值

  • 相关阅读:
    leetcode 18 4Sum
    leetcode 71 Simplify Path
    leetcode 10 Regular Expression Matching
    leetcode 30 Substring with Concatenation of All Words
    leetcode 355 Design Twitte
    leetcode LRU Cache
    leetcode 3Sum
    leetcode Letter Combinations of a Phone Number
    leetcode Remove Nth Node From End of List
    leetcode Valid Parentheses
  • 原文地址:https://www.cnblogs.com/sere/p/4630997.html
Copyright © 2011-2022 走看看