nancy
nancy

Reputation: 175

Sending json from Javascript to Javascript

I have a js inside a jsp from where I want to send a json in another js.

In jsp the console.log(html_out); prints the json right.

  $.ajax({
     //ajax code
     },
        async: true
    })
    .done(function(html_out) {
        console.log(html_out);
        drawTable(html_out);

    })

Output for console.log(html_out):

{ title: "hello1", name: "nam1" },{ title: "hello2", name: "nam2" }

But, in js the json doesn't put the data right inside the table i want to put them. The console.log(rowData); displays :

 { 
 t
 i
 t
 l
 e
 :
 "
 h
 ...
 ...

Here is my code in the js that i want to print my json:

function drawTable(data){

for (var i=0; i<data.length; i++){
    drawRow(data[i]);
}
}
function drawRow(rowData) {
   console.log(rowData);
var row = $("<tr />")
$("#farmacyDataTable").append(row);
row.append($("<td>" + rowData.title + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));

}

Upvotes: 1

Views: 63

Answers (3)

Ruan Mendes
Ruan Mendes

Reputation: 92274

As mentioned by dfsq, you have to parse the JSON string into a JavaScript object, right now you are iterating over the string

$.ajax({
   //... ajax code
   async: true, // Not needed, it default to async: true, async:false is deprecated
   // If you add the line below, you don't need to parse the response
   // dataType: 'json'
})
.done(function(html_out) 
    drawTable(JSON.parse(html_out));
})

If you correctly set the MIME type for the response (on the server), you will not need to call JSON.stringify

http://api.jquery.com/jquery.ajax/

dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

Upvotes: 1

Jiri Cap
Jiri Cap

Reputation: 166

I made some corrections to your code, you can play with it here: https://jsfiddle.net/mzf4axc0/

var jsonData=[{ title: "hello1", name: "nam1" },{ title: "hello2", name: "nam2" }];

function drawTable(data){
    for (var i=0; i<data.length; i++){
        drawRow(data[i]);
    }
}

function drawRow(rowData) {
  console.log(rowData);
  var row = $("<tr /><td>" + rowData.title + "</td><td>" + rowData.name +  "</td>" + "</tr>");
  $("#farmacyDataTable").append(row);
}

$(document).ready(drawTable(jsonData));

Upvotes: 0

Arman Ozak
Arman Ozak

Reputation: 2344

var parsed = JSON.parse(html_out);
drawTable(parsed);

Please take a look at the JSON.parse MDN page for browser compatibility.

Upvotes: 1

Related Questions