user3240544
user3240544

Reputation: 267

How is the data passed from JSON to AJAX?

I'm facing difficulties understanding the logic here. Ok, so let's say I have a class

@RequestMapping(value="/GetPersons", method = RequestMethod.GET)
    public void loadPersons(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
        OutputStream out = response.getOutputStream();
        List<Person> persons = personDAO.loadPersons();
        Iterator iterator = persons.iterator();

        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        while (iterator.hasNext()) {
          JSONObject object = new JSONObject();
             object.put("name", person.GetName());
            jsonArray.add(object);
        }
        jsonObject.put("data", jsonArray);
        OutputStreamWriter writer = new OutputStreamWriter(out);

        try {
            writer.write(jsonObject.toString());
        }finally {
            writer.close();
        }
    }

And then I have a simple script in my index.jsp

function loadPersons(json) {
    var obj = JSON.parse(json);
    var Person = obj.data;

    for (i = 0; i < myArr.length; i++) {
        $('#myId).append('<li><a href="#" PersonId="+Person[i].name+">Test</a></li>');

    }
}

$.ajax({
    url: "http://localhost:8080/Persons/getPersons",
    success: function (data) {
        loadPersons(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
});

So my question is the following... What is the logic that goes on here? How is the JSONObject data passed to the $.ajax success and the function. The function takes an argument "data" but what is going to be passed? The whole getPersons method from the java or?

The point here is to dynamically populate a simple dropdown by calling json object with ajax.

Upvotes: 0

Views: 494

Answers (3)

dReAmEr
dReAmEr

Reputation: 7196

First click the link http://localhost:8080/Persons/getPersons on any browser,if your spring service is running currently,you will see JSON data in your browser. The same data is getting fetched by the AJAX call inside your index.jsp.

$.ajax({
    url: "http://localhost:8080/Persons/getPersons",
    success: function (data) {
        loadPersons(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
});

P.S - i think you will have to add below line also to this ajax call

dataType :'json'

In the ajax call, success and failure are callback function which are invoked when browser get the response from server,success is executed in case of (2XX) while failure is invoked in case of error response,success function takes an argument data,which is JSON,same as you would have seen in your previous step.

Then as you received data from server,it is in JSON format(I suppose),you will have to parse it to convert it to object,and then you are fetching the data and setting it to the html elements.

$('#myId).append('<li><a href="#" PersonId="+Person[i].name+">Test</a></li>');

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85799

In this specific case, you're writing the JSON string content directly in the response of the request. This is done in these lines:

//Obtain the output stream from the response
OutputStream out = response.getOutputStream();
//Wrap the output stream into a writer
OutputStreamWriter writer = new OutputStreamWriter(out);
try {
    //write in the writer that will write on the HTTP response
    writer.write(jsonObject.toString());
}finally {
    //close writer and free resources
    writer.close();
}

So, the response from the server will be a string that contains your data. This comes from these lines of code:

JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
while (iterator.hasNext()) {
  JSONObject object = new JSONObject();
     object.put("name", person.GetName());
    jsonArray.add(object);
}
jsonObject.put("data", jsonArray);

Then, the $.ajax from jquery will execute the callback function defined in success, where it receives the response from the server as the argument:

$.ajax({
    //removed code for explanation purposes...
    success: function (data) {
        //data is the response from the server on a successful execution
        //of the HTTP request to the server
        //do something here with the response from the server
        //in this case, call the loadPersons function
        loadPersons(data);
    }
});

In loadPersons function, you deserialize the data from the json string into a JavaScript json object, then create HTML from the json data there.

Upvotes: 0

Shawn Bush
Shawn Bush

Reputation: 642

In your loadPersons method, you use the JSONObject and JSONArray classes to build a Java representation of a JSON object that will look like this:

{
   "data": [
      {
         "name": "whatever person.getName() evaluated to"
      },
      {
         "name": "another person.getName() call"
      }
   ]
}

This is the JSON data that is sent, as text, in the response from your servlet.

The jQuery ajax function does additional work with this response, finally turning it into a Javascript object, which is then passed to your success callback as the data parameter. This Javascript object looks similar:

{
   data: [
      {
         name: "whatever person.getName() evaluated to"
      },
      {
         name: "another person.getName() call"
      }
   ]
}

And you could access the value of the first name with: data.data[0].name

Upvotes: 1

Related Questions