gpt4 book ai didi

javascript - 如何使用 AJAX 从 jsp 中的 servlet 检索多个值

转载 作者:行者123 更新时间:2023-11-29 18:53:09 25 4
gpt4 key购买 nike

我有这个 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 服务和客户端之间共享数据,您必须选择最适合您需求的协议(protocol)/策略(XML、JSON...)。

由于您使用的是 JavaScript,我建议您阅读有关 JSON(代表“JavaScript 对象表示法”)的内容。

在您的示例中,您应该生成并返回一个 JSON 字符串(带有正确的 Content-type header )- 您可以阅读有关 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
}

关于javascript - 如何使用 AJAX 从 jsp 中的 servlet 检索多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50423065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com