0

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);
  }
2
  • Presumably your servlet is listening on some port / url -- do you know the uri? Commented Apr 10, 2013 at 5:50
  • Probably this can help you <stackoverflow.com/questions/15801871/…> Commented Apr 10, 2013 at 5:51

2 Answers 2

1

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

});
Sign up to request clarification or add additional context in comments.

Comments

1

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....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.