Rodrick Rodrick - 7 months ago 8
Javascript Question

How to format a JSON/XML answer from a REST call using jQuery or any other thing?

I have an HTML that invoke a REST webservice and get the JSON/XML answer.
What I have to do to get the answer on readable way?

Could I use some ajax to not refresh the page? How?

My HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Specify Parameters</title>

<script>
function execute() {
var param1 = $("#param1").val();
var param2 = $("#param2").val();
var format = $('input:radio[name=format]:checked').val();
var url = "http://localhost/something?rs=" + param1 + "|" + param2
+ "&format=" + format;

location.href = url;
}
</script>

</head>
<body>

<div id="mainDiv">

<div class="param1">
<label for="param1">Param1:</label>
<input type="text" id="param1" size="10" value="514" />
</div>

<div class="param2">
<label for="param2">Param2:</label>
<input type="text" id="param2" size="10" value="PI761" />
</div>

<div id="radioButtonsDiv">
<input type="radio" name="format" value="json" checked>JSON
<input type="radio" name="format" value="xml">XML
</div>

<div class="submitDiv"><input type='button' id='submit' onClick='execute()' value="Submit"/><div class="submitDiv">

</div>

</body>
</html>


Response example:

{
"result": [{
"string01": "104",
"string02": "104 - blablabla",
"string03": "104",
"string04": "blobloblo",
"string05": "blablabla",
"dest": [{
"pred": [{
"time": 1461348846,
"sec": 102,
"min": 1,
"string11": "514-String",
"string12": "Some String",
"string13": "Some other String",
"number": 0
}]
}]
}]
}

Answer

I got the output in HTML format using jQuery like this:

$.getJSON(URL, function(data) {
    $('#divname').html(data.result[0].string05 + ',' + data.result[0].dest[0].pred[0].time);
})

HTML:

<div id="divname"></div>
Comments