@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("name"); String pwd = req.getParameter("pwd"); PrintWriter writer = null; try{ resp.setContentType("text/html"); writer = resp.getWriter(); writer.print("{name:‘"+name+"‘,pwd:‘"+ pwd +"‘}"); }finally{ if(writer != null){ writer.close(); } } }
<script type="text/javascript"> function showname(){ $.get("test",{name:$("#name").val(),pwd:$("#pwd").val()},function(data){ var obj = eval(‘(‘+ data+‘)‘); alert(obj.name); }); } </script> <body> name: <input id="name" type="text" name="name"/> passWord:<input id="pwd" type="text" name="pwd"/> <input type="button" id="stn" value="确定" onclick="showname()"> </body>
以上writer.print中如果参数name和pwd左右不加单引号,js中就不能把字符串解析成json对象取name的值,至于为什么,应该是因为{name:name,pwd:pwd}这样子的字符串,json不认识第二个name是什么吧,如果是数字则可以。
时间: 2024-11-09 01:40:37