如何从DB(MYSQL)获取信息并将值存储在JSP中的json中

时间:2015-03-03 15:29:54

标签: mysql json jsp

我的代码在这里

<script type="text/javascript">
   $(document).ready(function() {
          $("#messageReceiver").tokenInput([
                {id: 7, name: "Ruby"},
                {id: 11, name: "Python"},
                {id: 13, name: "JavaScript"},
                {id: 17, name: "ActionScript"},
                {id: 19, name: "Scheme"},
                {id: 23, name: "Lisp"},
                {id: 29, name: "C#"},
                {id: 31, name: "Fortran"},
                {id: 37, name: "Visual Basic"},
                {id: 41, name: "C"},
                {id: 43, name: "C++"},
                {id: 47, name: "Java"}
            ]);
        });
     </script>

我想将数组的内容替换为数据库中的名称。 例如{name:“Ruby”}被{name:“A Name from DB”}取代 我使用Jsp顺便说一句,该脚本是一个自动完成脚本

1 个答案:

答案 0 :(得分:0)

您可以将JSONArray发送到jsp,只需将tokenInput方法放入其中。

的Servlet

User user1=getUserFromDB(1);
User user2=getUserFromDB(2);

JSONObject json = new JSONObject();
json.put(user1.getUserID, user1.getUserName);
json.put(user2.getUserID, user2.getUserName);

JSONArray array = new JSONArray();
array.put(json);
request.setAttribute("subjects", array);
request.getRequestDispatcher("myJSP.jsp").forward(request,response);

JSP:

$(document).ready(function() {
   var subjects='${subjects}';
    $("#messageReceiver").tokenInput(subjects);

});