Reputation: 178
I'm trying to learn Jquery. I have a problem: I have to send a json dynamically as param of a function. My code is this:
$('#grafo').append('<a class="list-group-item graph" href="#" id="' + nome.replace(/ /g,'') + '" onclick="printAnnotation(\'' + json + '\',\'' + index + '\')">' + name + '</a>');
I would like to get a json, but the results is a string.
How can I fix that ?
PS: sorry for my bad English.
Upvotes: 1
Views: 2445
Reputation: 5880
You can convert the string to JSON using JSON.parse()
method or the jQuery equivalent $.parseJSON
.
Note: When passing a Javascript object embedded in HTML (for instance in a function call), stringify the object in accordance to JSON format using JSON.stringify()
method:
$('#grafo').append('<a class="list-group-item graph" href="#" id="' + nome.replace(/ /g,'') + '" onclick="printAnnotation(\'' + JSON.stringify(json) + '\',\'' + index + '\')">' + name + '</a>');
Upvotes: 0
Reputation: 316
Try adding an event handler from script instead ( https://api.jquery.com/click/ ):
$('#grafo').click(
function()
{
printAnnotation( json, index );
}
);
Upvotes: 0
Reputation: 77278
If you're embedding your JSON inline in the DOM like that you're stuck with a string. This isn't a big deal though, because you can turn the string into a JSON object inside your function. Like so:
function printAnnotation(jsonString, index) {
var json = JSON.parse(jsonString);
// do stuff
}
Upvotes: 1