get value from servlet using ajax

I want to fetch object from servlet.

I try below code but I get "[object Object]" . I want "Description" value.

I got out in browser when I run http://www.host.com/f/ServletToJSP1/*

o/p {"Description":"Nutanix provides disruptive datacenter infrastructure solutions that are hyper-efficient, massively scalable and elegantly simple."}

in console log :Uncaught ReferenceError: google is not defined

How can I do that ?

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 code

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);
                }
            });

Are you developing in Chrome? You can open the dev tools with CTRL+SHIFT+I then open the Console.

Instead of alert(respone) try console.log(response) to have a deeper look into the variable.


Try

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

and in your servlet code try to add out.flush();

链接地址: http://www.djcxy.com/p/46082.html

上一篇: DecimalFormat.format()更快的替代方法?

下一篇: 使用ajax从servlet获取值