【问题标题】:Sending data/object to ajax将数据/对象发送到 ajax
【发布时间】:2015-05-03 20:00:30
【问题描述】:

在将对象转换为json 后,如何将数据发送到 ajax 调用?

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
   response.setContentType("text/plain");
   PrintWriter writer = response.getWriter();
   LinkedList list = new LinkedList();
   list.add("first");
   list.add("second");
   list.add("third");
   Gson gson = new Gson();
   gson.toJson(list);
   writer.println("From servlet");
}

阿贾克斯:

$.ajax( {
                    url : 'http://localhost:8081/Football/SendToAjax',
                    type : 'GET'
                })
                .done(function(message) {
                    alert(message);
                }).
                fail(function(message) {
                    alert(message);
                });

【问题讨论】:

  • 您可以用作 message[0] 和更多索引。正如我在回答中提到的那样。

标签: java ajax json servlets gson


【解决方案1】:

你也可以写成 JSONObject 如下

JSONObject json = new JSONObject();
json.put("list", list);
writer = response.getWriter();
writer.println(json.toString());

然后你可以在你的 ajax 函数中使用它:

$.ajax({
type: 'GET',
url: urlPath,
dataType : "json",
success: function(message){// message is returned message that was written in json
 // use data as message[0]
   for(i = 0; i <message.length; i++){
       alert(message[i]);
 }
 }
 }
 );

【讨论】:

    【解决方案2】:

    在 ajax 中使用 dataType:"json",

    $.ajax( {
    url : 'http://localhost:8081/Football/SendToAjax',
    type : 'GET',
    dataType:"json"
    })
    .done(function(message) {
    alert(message);
    }).
    fail(function(message) {
    alert(message);
    });
    

    在小服务程序中

    JSONObject object = new JSONObject();
    
    object.accumulate("list", list);
    

    【讨论】:

      【解决方案3】:

      写回 gson.toJson() 返回的字符串。此外,您可以在响应中设置正确的内容类型。

         String out = gson.toJson(list);
         response.setContentType("application/json");
         writer.println(out);
      

      【讨论】:

      • jquery 端如何接收?
      • 将dataType属性设置为json,使用success()回调函数(而不是.done)直接将response作为js对象访问。 success:function (responseTxt, status, jqxhr){ //responseTxt.someProperty;}
      猜你喜欢
      • 2017-07-29
      • 1970-01-01
      • 2021-12-31
      • 2015-09-24
      • 2015-11-29
      • 2020-09-20
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      相关资源
      最近更新 更多