上一篇【http://blog.csdn.net/J080624/article/details/54948321】的讲解传到后台的参数形式为username=yanshi02&passWord=123456 字符串。
那么如果传到后台的格式是JSON呢?
queryString = $('#editform').serializeArray();//objectqueryString = JSON.stringify(queryString);//string$.get(url,queryString,function(data){});【jsp页面】
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'post.jsp' starting page</title> <meta http-equiv="PRagma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/CSS" href="styles.css"> --> <script type="text/Javascript" src="./scripts/jquery-1.7.2.js"></script> <script type="text/javascript"> var url =""; var queryString = ""; $(function(){ $("input[type='button']").click(function(){ url = $("#editform").attr("action"); //queryString = $('#editform').serialize(); queryString = $('#editform').serializeArray(); queryString = JSON.stringify(queryString);//string $.get(url,queryString,function(data){ alert(data); } ,"json"); }); }); </script> </head> <body> This is my JSP page. <br> <form id="editform" action="getServlet2" method="get"> <input type="text" name="username" value=""/> <input type="password" name="password" value=""/> </form> <input name="post" type="button" value="提交"/> </body></html>【后台接收方法】
思路:
使用request.getQueryString();
获取传输的数据。
因为是JSON形式,所以不适宜用request.getParameterMap
;
因为是 get 请求,数据都在Query String Parameters 里面,不能使用request.getReader
;
result as follows :
//servlet初始化getServlet init()....//获取的string,有大量转译字符[{%22name%22:%22username%22,%22value%22:%22yanshi02%22},{%22name%22:%22password%22,%22value%22:%22123456%22}]//解码后的字符串[{"name":"username","value":"yanshi02"},{"name":"password","value":"123456"}]//返回的jsonresultJson ..."[{/"name/":/"username/",/"value/":/"yanshi02/"},{/"name/":/"password/",/"value/":/"123456/"}]"题外话:
如果请求格式为$.get(url,{mydata:queryString},function(data){});
呢?
数据在 Query String Parameters 里面。
一般有两种思路:
① 使用request.getParameterMap
;
② 使用 request.getQueryString
;
附结果如下:
//获取的stringmydata=%5B%7B%22name%22%3A%22username%22%2C%22value%22%3A%22yanshi02%22%7D%2C%7B%22name%22%3A%22password%22%2C%22value%22%3A%22123456%22%7D%5D//解码后的stringmydata=[{"name":"username","value":"yanshi02"},{"name":"password","value":"123456"}]//返回的jsonresultJson ..."mydata=[{/"name/":/"username/",/"value/":/"yanshi02/"},{/"name/":/"password/",/"value/":/"123456/"}]"第三种思路 !!!
点击查看第三种思路【http://blog.csdn.net/J080624/article/details/54950679】
新闻热点
疑难解答