我無法以JSON
格式從我的jsp
到servlet
控制器發送數據。我想,我在調用servlet的ajax
時出錯了。下面是我的代碼:無法將「JSON.stringify」數據發送到servlet
JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script>
var SendInfo=[];
$(document).ready(function(){
$("#but").click(function(){
$(".tabclass tr td input[type='checkbox']:checked").each(function(){
var sibs=$(this).parent().siblings("td");
var v0= $(this).val();
var v1=$(sibs[0]).text();
var v2=$(sibs[1]).children("select[name='address']").val();
var domain = {
id:v0,
name: v1,
address: v2
}
SendInfo.push(domain);
alert(v0+" & "+v1+" & "+v2);
});
$.ajax({
type: "POST",
url: "s1.do",
data: JSON.stringify({ students: SendInfo }), // might be wrong here or is it correct way to send data?
success: function(data, status){
alert("Data: " + data + "\nStatus: " + status);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
});
</script>
</head>
<body>
<table border="1" class="tabclass">
<th>select</th><th>Name</th><th>Address</th>
<tr>
<td><input type="checkbox" name="selectCheck" class="select" id="ch1" value="1"/> </td>
<td><span class="name">Nitin</span></td>
<td><select name="address">
<option>Gurgaon</option>
<option>Noida</option>
<option>Rohini</option>
</select></td>
</tr>
<tr>
<td><input type="checkbox" name="selectCheck" class="select" id="ch2" value="2"/> </td>
<td><span class="name">Abc</span></td>
<td><select name="address">
<option>Gurgaon</option>
<option>Noida</option>
<option>Rohini</option>
</select></td>
</tr>
<tr>
<td><input type="checkbox" name="selectCheck" class="select" id="ch3" value="3"/> </td>
<td><span class="name">Xyz</span></td>
<td><select name="address">
<option>Gurgaon</option>
<option>Noida</option>
<option>Rohini</option>
</select></td>
</tr>
</table><br><br>
<button id="but">Test</button>
<br></br><button id="but2">Test2</button>
</body>
</html>
的Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String abc = request.getParameter("students");
System.out.println("JSON > "+abc);
}
我收到輸出控制檯:
JSON > null
我可以用request.getParameter如果我使用AJAX的'$ .post'方式接收數據()方法。我想問,爲什麼這種行爲不可能用於'$ .ajax' – JPG