3)通过$.post()方法返回对象
当通过$.post()方法字符串跟数组依然满足不了需要的时候,还可以通过此种方法返回对象类型的数据,在这里依旧采用登录的案例来讲解,具体实现如下:
1)依旧是建立一个用于登录的login.html页面,代码如下:
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>登录界面</title> <script language="JavaScript" src="../jQuery/jquery1.8.2.js"></script> <script> $(function(){ $("#submit").click(function(){ $.post( "../LoginServlet", { name:$("#name").val(), password:$("#password").val() }, function(data){ alert("返回的数据类型是"+data); var value = JSON.parse(data); alert("解析后的数据类型是"+value.obj[1]); var name = value.obj[1]; var password = value.obj[2]; if(value.obj[0]=="success"){ alert("登录成功"+"\n"+"姓名="+name+"——"+"密码="+password); } if(data=="failure"){ alert("登录失败"); } }, "html" ); }) }) </script> <style> body{width:300px; height:200px; margin:0 auto;} fieldset{ width:300px; } table{ width:300px; height:100px;} </style> </head> <body> <fieldset> <legend>登录界面</legend> <form method="post"> <table> <tr><td>姓名:</td><td><input type="text" name="name" id="name"/></td></tr> <tr><td>密码:</td><td><input type="password" name="password" id="password"/></td></tr> </table> <input type="button" value="提交" style="margin-left:66px; width:70px;" id="submit"> <input type="reset" value="重置" style="width:70px;"/> </form> </fieldset> </body> </html> |
2)建立一个用于接收请求参数的Servlet类型的LoginServlet.java,具体实现代码如下:
package zjh.javaee.servlet;
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson; import com.google.gson.JsonObject;
@WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L;
public LoginServlet() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决乱码问题 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); //接收请求的参数 String userName = request.getParameter("name"); String userPassword = request.getParameter("password"); List<String> list = new ArrayList<String>(); PrintWriter pw = response.getWriter(); String str = ""; //判断是否为空,如果不为空,则将姓名传递到show.html页面中 if(userName.equals("")||userName==null||userPassword.equals("")||userPassword==null){ str = "failure"; }else{ str = "success"; } Gson gson = new Gson(); JsonObject object = new JsonObject(); list.add(str); list.add(userName); list.add(userPassword); object.add("obj",gson.toJsonTree(list)); pw.print(object.toString()); }
}
|
3)解析前的数据为:
|
解析后的数据为:
|
当返回的数据经过解析时,就可以通过value.obj[0]、value.obj[1]、value.obj[2]依次取得第一个、第二个、及第三个的值,其中obj为在后端传递数据时为对象取得的名字,最终结果如下:
|