1. 程式人生 > >Java通過Json傳遞資料給JavaScript

Java通過Json傳遞資料給JavaScript

<%@ page contentType = "text/html;charset=UTF-8" language = "java" %>
<%@ page import="net.sf.json.JSONObject" %> 
<html>
  <head>
    <title>HS</title>
  </head>
  <body>
<%
    HashMap<String, String> test = new HashMap<String, String>();
    test.put("w", "www");
    test.put("s", "sss");
    test.put("k", "kkk");
    JSONObject jsonObject = JSONObject.fromObject(test);
    System.out.println(jsonObject);
    session.setAttribute("wsk", jsonObject);
%>
  <%= session.getAttribute("wsk")%>
  </body>
<script>
    var wsk = <%= session.getAttribute("wsk")%>;
    var x = "w";
    var y = "s";
    var z = "k";
    alert(eval("wsk." + x) + eval("wsk." + y) + eval("wsk." + z));
</script>
</html>