我有这个ajax
javascript代码,调用servlet
来检索两个值(名字,电话)。我知道如何从servlet获取单个值而不是多个值。
这是我的ajax
<script>
function getCustomerDetailsAjax(str) {
str = $('#customerId').val();
if (document.getElementById('customerId').value <= 0) {
document.getElementById('firstName').value = " ";
document.getElementById('telephone').value = " ";
document.getElementById('vehicleMake').value = " ";
document.getElementById('vehicleModel').value = " ";
document.getElementById('vehicleColor').value = " ";
} else {
$.ajax({
url: "GetCustomerDetails",
type: 'POST',
data: {customerId: str},
success: function (data) {
alert(data); //I want to get 2 servlet values and alert them here. How can I do that?
}
});
}
}
</script>
这是我的servlet
public class GetCustomerDetails extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
int customerId = Integer.valueOf(request.getParameter("customerId"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
ps.setInt(1, customerId);
ResultSet result=ps.executeQuery();
if(result.next()){
out.print(result.getString("firstname")); //I want to send this value
out.print(result.getString("telephone")); //and this value
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
这是从servlet
检索数据的部分,如何从中获取多个值并发出警报?
success: function (data) {
alert(data); //I want to get 2 servlet values and alert them here. How can I do that?
}
谢谢!
答案 0 :(得分:2)
要在Web服务和客户端之间共享数据,您必须选择最适合您需求的协议/策略(XML,JSON ...)。
由于您使用的是JavaScript,我建议您阅读JSON(代表“JavaScript Object Notation”)。
在您的示例中,您应该生成并返回一个JSON字符串(具有正确的Content-type标头) - 您可以阅读javax.json
包。使用JSON,您可以返回包含所选字段的数据结构。
类似的东西(未经测试 - 自编码Java以来已经很久了):
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
int customerId = Integer.valueOf(request.getParameter("customerId"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
ps.setInt(1, customerId);
ResultSet result=ps.executeQuery();
if(result.next()){
/* set response content type header: jQuery parses automatically response into a javascript object */
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
/* construct your json */
JsonObject jsonResponse = new JsonObject();
jsonResponse.put("firstname", result.getString("firstname"));
jsonResponse.put("telephone", result.getString("telephone"));
/* send to the client the JSON string */
response.getWriter().write(jsonResponse.toString());
// "{"firstname":"first name from db","telephone":"telephone from db"}"
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
在你的JS中(我想你正在使用jQuery,因为success
回调):
success: function (data) {
/* because you set the content-type header as 'application/json', you'll receive an already parsed javascript object - don't need to use JSON.parse. */
console.log(data);
/*
{
firstname: "first name from db",
telephone: "telephone from db"
}
*/
alert(data.firstname); //alert firstname
alert(data.telephone); //alert phone
}
答案 1 :(得分:0)
是的,您可以使用JSON执行此操作,正如之前的答案已经说明的那样,但我想补充一点,您可以采取一些措施来进一步简化代码,因为您使用的是jquery。
<script>
function getCustomerDetailsAjax(str) {
str = $('#customerId').val();
if (str <= 0) {
$('#firstName').val(" ");
$('#telephone').val(" ");
$('#vehicleMake').val(" ");
$('#vehicleModel').val(" ");
$('#vehicleColor').val(" ");
$('#firstName').val(" ");
} else {
//with jquery you can do this, which is much easier.
var params = {customerId: str}; //set paramaters
$.post("GetCustomerDetails", $.param(params), function(responseJson) {
//handle response
var firstname = responseJson.firstname;
var telephone = responseJson.telephone;
//now do whatever you want with your variables
});
}
}
</script>
此外,还有一些变化:
public class GetCustomerDetails extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
int customerId = Integer.valueOf(request.getParameter("customerId"));
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
ps.setInt(1, customerId);
ResultSet result=ps.executeQuery();
if(result.next()){
String firstname = result.getString(1); //firstname
String telephone = result.getString(2); //telephone
JsonObject jsonResponse = new JsonObject();
jsonResponse.put("firstname", firstname);
jsonResponse.put("telephone", telephone);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonResponse.toString());
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
}
}
还有其他方法可以将值从servlet发送到jsp / html页面。我强烈建议在How to use Servlets and Ajax查看BalusC的答案,这非常有帮助。