简体   繁体   中英

Get value of JSON object in using jquery

I created a java servlet in which I am using a JSON object and now I want to fetch the values from jSON object into my HTML page using Jquery but i don't know how to do it.

servlet code:

  ResultSet rs = st.executeQuery("Select * from SampleTable");
  JSONObject obj= new JSONObject();

  if(rs.next())
  {
      String fname=rs.getString(1);
      obj.put("status", "yes");
      obj.put("fname",fname);
      System.out.println(obj);
      out.print("Hello" + obj);

  }
  else
  {
      obj.put("status", "no");
      out.print(obj);
  }

Set response.setContentType("application/json"); in your Servlet before response.getWriter() ;

Add jQuery Js

Then call getData() like button click.

<script type="text/javascript">
  $(function(){
      function getData() {

          $.ajax({
                url : 'getDataServlet', // Your Servlet mapping
                type : 'POST',
                dataType : 'json, 
                success : function(response) {
                    alert(response.status);
                },
                error : function(request, textStatus, errorThrown) {
                    alert(errorThrown);
                }
            });
      }

});

In your javascript code, you can simply write:

<script type="text/javascript">
$(function(){
  function getData() {

      $.ajax({
            url : 'getDataServlet', 
            type : 'POST',
            dataType : 'json, 
            success : function(response) {
                var status = data.status;
                var fname = data.fname;
            },
            error : function(error) {
                //error handling....
            }
        });
  }

status and fname variables contain the values which you put in your server side java code.

In general, for getting any value from a JSON Object in javascript, you just need to know the key. var value1 = object.key1; var value2 = object.key2;

and so on....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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