I am making an Ajax call in my JSP which is recieving a JSON response.
Running alert('Ajax Response ' + respArr);
gives the following screen:
The Java server-side code:
public void doGet(HttpServletRequest request, HttpServletResponse res) throws IOException, ServletException {
try {
String fromDate = request.getParameter("drFrom");
String toDate = request.getParameter("drTo");
JSONArray jsonArray = chartData.getCCSBJson(fromDate, toDate);
res.setContentType("application/json");
res.getWriter().write(jsonArray.toString());
}
The JavaScript:
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(xmlhttp.responseText != null) {
var respArr = xmlhttp.responseText;
var jsonData = eval("(" + respArr + ")");
alert('JSON Chart ' + jsonData); // The line from above
var obj = JSON.parse(xmlhttp.responseText);
alert('JSON Parse' + obj);
The JSON that is being returned:
[
{
"chart":{
"caption":"",
"exportDataFormattedVal":"1",
"numberPrefix":"",
"showexportdatamenuitem":"1",
"xAxisName":"Bureau usage",
"yAxisName":"count"
},
"data":[
{
"label":"SB AutoDecison",
"value":"0"
},
{
"label":"CC AutoDecison",
"value":"0"
},
{
"label":"CC Judgemental",
"value":"0"
},
{
"label":"SB Judgemental",
"value":"0"
}
]
}
]
The alerts result:
alert('JSON Chart ' + jsonData) // JSON Chart[object Object]
alert('JSON Parse ' + obj); // JSON parse[object Object]
What I want is to parse the object and generate an Excel sheet out of the content.
When I try to loop:
var jqueryData = jQuery.parseJSON(respArr);
var obj = JSON.parse(xmlhttp.responseText);
for (var i in obj) {
alert('For loop string' + obj[i]);
}
It throws some 7 or 8 alerts with JavaScript code
for (i = 0; i < 5; i++) {
alert(i + ' of respArr ' + respArr[i]);
}
Gives letter after letter of the JSON: [
, {
, "
, c
, h
, and so on for each iteration of the loop.
Can I not just traverse the JSON like respArr[0].data
or respArr[0].chart
?
See Question&Answers more detail:
os