前台:js
$.get(
"TestServlet",
{name:"name1", pwd: "123", "color[]": ["red", "green", "black"]},
function(data, status, xhr) {
alert("result " + data + ";" + status);
}
);
后台:
TestServlet.java
doGet
String[] color = request.getParameterValues("color[]");
for(String c : color) {
Sysout(c);
}
Result:
red
green
black
获取Servlet JSON数据,采用两种JQuery方法 $.get 和$.getJSON
JsonServlet.java
//flag 判断 是 $.get 还是$.getJSON方法 0代表 get
//测验了一下,貌似 get 方法 需Server 声明为 JSON数据,但 getJSON 会自动转化 数据为 JSON 故可以不用声明JSON类型
if(request.getParameter("flag").equals("0")) {
response.setContentType("application/json");
}
//构造json 数据
String jsonArray = "[{\"name\", \"zhangsan\", \"address\", \"shanghai\"}, {\"name\", \"lisi\", \"address\", \"beijing\"}]";
PrintWriter pw = response.getWriter();
pw.write(jsonArray);
pw.close();
jsp 页面:
<div id="show1">$.get to get JSON from Server</div><br>
<div id="show2">$.getJSON to get JSON from serer</div><br>
<button id="showJson1">$.get</button><br>
<button id="showJson2">$.gerJSON</button>
json.js
$(document).ready(
function() {
// $.get method must receive the JSON data from server, so
// we should decare the setContentType("application/json") in
// servlet
$("#showJson1").click(
function() {
$.get("JsonServlet", {
flag : "0"
}, function(data) {
alert(data);
$("#show1").empty();
$.each(data, function(index, d) {
$("#show1").append(
"<span>" + "json " + index + ": name "
+ d.name + ", address "
+ d.address + "</span><br>");
});
});
});
// $.getJSON method will automatically transform the data from
// server
// to JSON pattern and output it
// that is to say we don't need to declare the
// contentType("application/json") in servlet
$("#showJson2").click(
function() {
$.getJSON("JsonServlet", {
flag : "1"
}, function(data) {
alert(data);
$("#show2").empty();
$.each(data, function(index, d) {
$("#show2").append(
"<span>" + "json " + index + ": name "
+ d.name + ", address "
+ d.address + "</span><br>");
});
});
});
});
输出:
json 1: name zhangsan, address beijing
json 1: name zhangsan, address beijing