繁体   English   中英

使用ajax从servlet获取价值

[英]get value from servlet using ajax

我想从servlet中获取对象。

我尝试下面的代码,但得到“ [object Object]”。 我想要“描述”值。

运行http://www.host.com/f/ServletToJSP1/*时,我在浏览器中退出了

o / p {“ Description”:“ Nutanix提供了破坏性的数据中心基础架构解决方案,这些解决方案非常高效,可大规模扩展并且非常简单。”}

在控制台日志中:未捕获ReferenceError:未定义google

我怎样才能做到这一点 ?

jsp code
                  $.ajax({
                        url : 'ServletToJSP1', 
                        type : 'GET',
                        dataType : 'json', 
                        success : function(response) {
                            //response = $.parseJSON(response);
                            alert(response);
                        },
                        error : function(error) {
                            //error handling....
                            alert(error);
                        }
                    });

servlet代码

JSONObject objTw = new JSONObject();
      objTw.put("Description", "Nutanix provides disruptive datacenter infrastructure solutions that are hyper-efficient, massively scalable and elegantly simple.");
PrintWriter out = response.getWriter();
response.setContentType("application/json"); 
response.setCharacterEncoding("utf-8"); 
  out.println(objTw);

访问响应对象上的description属性。

          $.ajax({
                url : 'ServletToJSP1', 
                type : 'GET',
                dataType : 'json', 
                success : function(response) {
                    //response = $.parseJSON(response);
                    alert(response.Description);
                },
                error : function(error) {
                    //error handling....
                    alert(error);
                }
            });

您正在使用Chrome开发吗? 您可以使用CTRL + SHIFT + I打开开发工具,然后打开控制台。

代替alert(respone)尝试使用console.log(response)对变量进行更深入的了解。

尝试

success : function(response) {
                  alert(response[0].Description);
                },

并在您的Servlet代码中尝试添加out.flush();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM