我開始學習與jQuery的Ajax,我試了很多谷歌搜索,我不能得到這個測試代碼工作,你能告訴我什麼是我做錯了?會發生什麼是ajax不會創建表。這裏是我的代碼:我不能得到這個簡單的Ajax代碼工作
的JSP:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery.js"></script>
<title>My First Web App</title>
<script type="text/javascript">
$(document).ready(function{
$.ajax({
type: "GET",
url: "users",
dataType: "xml",
success: function(xml){
$("#content").append("<table>");
$(xml).find("user").each(function(){
var firstName = $(this).find("firstName").text();
var lastName = $(this).find("lastName").text();
var password = $(this).find("password").text();
var email = $(this).find("email").text();
$("#content").append("<tr>");
$("#content").append("<td>" + firstName + "</td>");
$("#content").append("<td>" + lastName + "</td>");
$("#content").append("<td>" + password + "</td>");
$("#content").append("<td>" + email + "</td>");
$("#content").append("</tr>");
});
$("#content").append("</table>");
}
});
});
</script>
</head>
<body>
<div id="content"></div>
</body>
該servlet:
@WebServlet("/users")
public class users extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public users() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml;charset=UTF-8");
usuarioDAO uDAO = new usuarioDAO();
response.getWriter().write(uDAO.getAllUsers());
}
usuarioDAO:
public String getAllUsers()
{
String xml = "";
xml += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
xml += "<users>";
try
{
getAllUsers = con.prepareStatement("SELECT * FROM users");
synchronized(getAllUsers)
{
ResultSet res = getAllUsers.executeQuery();
while (res.next())
{
xml += "<user>";
xml += "<firstName>" + res.getString("firstName") + "</firstName>";
xml += "<lastName>" + res.getString("lastName") + "</lastName>";
xml += "<password>" + res.getString("password") + "</password>";
xml += "<email>" + res.getString("email") + "</email>";
xml += "</user>";
}
}
getAllUsers.close();
}
catch (Exception ex)
{
System.out.println(ex);
}
xml += "</users>";
return xml;
}
而且僅此而已,你能不能請告訴我我做了什麼錯了嗎?
定義 「不工作」。它以什麼方式失敗?是否有某種錯誤?例外?代碼中的哪一點與預期行爲有偏差?在這一點上,預期與觀察行爲是什麼?那時相關對象的狀態是什麼? – David
你確定你的ajax調用的「url」是正確的嗎? – MilkyWayJoe
也許你忘了在這裏調用response.close()或response.flush()?如果它不會幫助,請您發佈一些額外的細節,可能是服務器日誌或螢火蟲日誌? –