Rabbit Rabbit - 3 months ago 12
HTML Question

How to parse data of various kinds from ajax reponse and present in UI?

Consider the following snippet with ajax call

var url ="/getcachevalue.do?method=getValueFromCache&key="+key.trim();
$.ajax({
url : url,
type : 'POST',
data : '',
success : function(req){
}
});


Where the url may bring back data of any kind say


  1. Number

  2. Array List

  3. String

  4. Boolean

  5. JSONObject

  6. JSONArray



I have to parse the result and display it in a JSP page.

Kindly suggest me a better way to parse the response which is of any of the above kind and present the resultant values in the UI for the given input (say here my input is
key
which is passed as input to the url)

Tried with the following:

if(responsevalue.startsWith("{")) {

$("#resulttable").append("<tr><th>KEY </th><th>VALUE</th></tr>");
var result = $.parseJSON(responsevalue);
$.each(result, function(key, value) {
var row = ("<tr><td>").concat(key).concat("</td><td>").concat(value).concat("</td></tr>");
$("#resulttable").append(row);
});

} else {

$("#resulttable").append("<tr><td>"+responsevalue+"</td></tr>");
}


But this produces values like


[object Object],[object Object],[object Object],[object Object]

Answer

You can use JSON.stringify(), JSON.parse(), typeof, Array.isArray(), Array.prototype.forEach() to iterate arrays, for..in loop to iterate object properties

function handleResponse(req) {

  var data = JSON.parse(JSON.stringify(req));
  // if `data` is `String`, `Number` or `Boolean` do stuff
  if (typeof data === "string" 
     || typeof data === "number" 
     || typeof data === "boolean") {
      console.log(data);
      return
  }
  // if `data` is `Array` or `Object` iterate array using `.forEach()`
  if (typeof data === "object" && Array.isArray(data)) {
    data.forEach(function(curr) {
      console.log(curr)
    })
  } 
  // else iterate object using `for..in`
  else {
    for (var prop in data) {
      console.log(prop, data[prop])
    }
  }

}

var expectedTypes = [1, "abc", true, ["abc", "def"], {abc: "def"}];

expectedTypes.forEach(handleResponse);