【发布时间】:2018-10-29 14:07:19
【问题描述】:
我有这个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?
}
谢谢!
【问题讨论】:
-
有人能帮帮我吗?
-
嗨。要在 Web 服务和客户端之间共享数据,您必须选择最适合您需求的协议/策略(XML、JSON...)。由于您使用的是 javascript,因此我建议您阅读 JSON(代表“JavaScript Object Notation”)。在您的示例中,您应该生成并返回一个 JSON 字符串(带有正确的 Content-type 标头) - 阅读有关 javax.json 包的信息。使用 JSON,您可以返回包含您选择的字段的数据结构。
-
@mrlew 你能告诉我一些例子吗?很大的帮助
-
我发布了一个答案。希望对您有所帮助。
标签: javascript java ajax servlets