简体   繁体   English

如何从我的休息服务发送一个json对象,以便我可以在客户端javascript解析

[英]How do I send a json object from my rest service so I can parse in out on the client side javascript

I just simply want to return a JSON object (using ajax) from my server to the client side - so I'm able to read the data in the client side 我只是想从我的服务器向客户端返回一个JSON对象(使用ajax) - 所以我能够在客户端读取数据

  @GET
  @Produces("application/json")
  @Consumes("application/json") 
  @Path("/getStatus/")

  public void getStatus(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response) throws ServletException,
      IOException
  {

      //create the JSON Object to pass to the client
      JSONObject object=new JSONObject();

      response.setContentType("text/javascript");    

      try
      {  
            object.put("name", nameDataFromClass);
            object.put("status",someData);

       }
       catch(Exception e)
       {  
            throw new ServletException("JSON Hosed up");  
       }  

       String json = object.toString();  
       response.getOutputStream().println(json);   
  }

This would be in the client side for JSP I want to extract the data out on the page 这将是JSP的客户端我希望在页面上提取数据

<html>
<head>

<!-- Calls in jQuery file -->
<script src="jquery.js"></script>

<title>JQuery Test</title>

<script>

    $.getJSON("http://localhost:8080/scout/rest/admin/mamba/getStatus",
    function(json) 
    {  
        alert("Server naame: " + json.name);  
    });  



</script>

</head>
<body>



</body>
</html>

The Jackson library should take care of marshalling json objects to your objects, and vice versa. Jackson库应该负责将json对象编组到您的对象,反之亦然。 Just create a simple POJO, like this: 只需创建一个简单的POJO,如下所示:

public class Mystatus{
   public String name;
   public String status;
   public Mystatus(){}  // a default empty constructor is needed
   public Mystatus(String name,String status){
     this.name=name;
     this.status=status;
   }
}

Then return this object from your RESTful webservice: 然后从RESTful Web服务返回此对象:

@GET
@Produces("application/json")
@Consumes("application/json") 
@Path("/getStatus/")

public Mystatus getStatus(
  @Context HttpServletRequest request,
  @Context HttpServletResponse response)
{
  response.setContentType("text/javascript");
  return new Mystatus("Hello","World");
}
  @GET
  @Produces("application/json")
  @Consumes("application/json")
  @Path("/status")
  // server:8080/server/rest/status
  public String getStatus(
      @Context HttpServletRequest request,
      @Context HttpServletResponse response) throws Exception
  {

    // Create a string to hold JSON
    String json;

      Collection<Server> svr = SomeHashMap.getStuff().values();

      JSONArray jArray = new JSONArray();

      for (Server i : svr)
      {
        JSONObject m = new JSONObject();

        ServerStatus status = i.getStatus();

        m.put("id", i.getId());
        m.put("name", i.getName());
        m.put("status", status.getState());

        jArray.add(m);
      }

      json = jArray.toString();
    }

    response.setContentType("text/javascript");
    response.getOutputStream().print(json);
    response.flushBuffer();

    return null;
}

index.jsp 的index.jsp

<head>
<script src="jquery-1.6.js"></script>
     <!--AJAX FOR STATUS PAGE REFRESH -->
     <script type="text/javascript">

    //when page is ready do the following
    $(document).ready(function()
    {
        // Disable caching of AJAX responses
        $.ajaxSetup ({cache: false});

        //set interval of refresh
        setInterval(doAjaxStuff, 1000);

        //function to call to fire off ajax
        function doAjaxStuff()
        {
            $.ajax
            ({
                url: "status", // <-- this refers to the Controller function above called "status()"
                dataType: 'json',
                success: function(json) 
                {
                    //traverse throught each element in the incoming JSON object
                    for(var i = 0; i< json.length; i++)
                    {
                        if(json[i].status ==  "ACTIVE")
                        {
                            $("#Status"+json[i].id).html("Running");
                        }


                    }               
                }
            });
        }
    });
    </script>

</head>

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

相关问题 如何在Rest Service中使用Jersey发送一个JSON对象 - How can I send a JSON object with Jersey in a Rest Service 如何从服务器端(Google App Engine,Cloud Endpoints)向我的客户端发送信息? - How can I send from the server-side (Google App Engine, Cloud Endpoints) the information to my client? 如何将json对象从jsp页面的jsp部分传递到javascript部分,即从服务器端到客户端? - How to pass a json object from the jsp part of a jsp page to the javascript part i.e from server side to client side? 如何从客户端JavaScript代码访问Java列表元素? - How can I access Java list elements from my client-side JavaScript code? 使用rest服务将文件从服务器端发送到客户端 - send a file from the server side to the client side using rest service 如何从Java对象向客户端发送spring消息 - How do I send a spring message to client from a Java object 如何将带有 JSON 数组的字符串解析为变量,以便我可以将它们放入 html 表中? - How do i parse a string with a JSON array to variables so i can put them in html tables? 如何使用Java将对象从服务器发送到客户端? - How I can send a object from server to Client in Java? 如何使用Java将对象从客户端发送到服务器? - How I can send a object from Client to Server in Java? 如何将图像从服务器发送到客户端? - How can i send images from server to my client?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM