java—将对象的arraylist返回到servlet的ajax调用

9udxz4iz  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(268)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

四年前关门了。
改进这个问题
我通过脚本中的ajax调用将字符串值传递给servlet,并在类对象中检索相应的数据并将其存储在arraylist中。现在我需要这个arraylist作为返回到ajax调用的“数据”。怎么做??

`<script>
        $(document).ready(function(){
            var selected;

            $('#txtboxvalue').change(function(){
                selected = $('#txtboxvalue').val();

                  $.ajax({
                    url: "Servlet2",
                    type: "Post",
                    data: {"txtboxvalue":selected},
                    success : function(data)
                        {
                        //here is where I want to access the returned arraylist
                        }   
});
        });
</script>

servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ArrayList<Cust> list2=cusName.dispCustomer2(abcd);
PrintWriter out = response.getWriter();
out.println(list2);
}

但这样的传球是行不通的

kwvwclae

kwvwclae1#

您希望返回复杂的数据:客户列表。一个好的格式应该是发送json格式的列表。
在服务器端,获取一个类似gson或jackson的json库,并将列表序列化如下:

response.setContentType("application/json");
new Gson().toJson(list2, response.getWriter());

在客户端,告诉jquery您期望一个json响应。

$.ajax({
      url: "Servlet2",
      type: "Post",
      data: {"txtboxvalue":selected},
      dataType: "json",
      success : function(list) {
          // list is the list as Javascript array
      }

相关问题