I'm only just learning javascript so I imagine this is relatively simple but it's been annoying me for a while now.
I have a function that simply displays some text that I am calling from a AJAX response. Here's my code.
if(this.responseText != null)
{
var text = "<ul>";
var object = eval("(" + this.responseText + ")");
var track;
for (var i = 0; i < object.length; i++)
{
track = object[i];
text += "<li><img src=\"" + track.artwork_url + "\"/>";
text += track.title;
text += "<ul><li><a href=\"#\" onclick=\"playTrack(" + track + ");return false;\">Play</a></li>"
text += "<li><a href=\"" + track.download_url + "?client_id=" + clientId + "\">Download</a></li></ul>"
text += "</li>";
}
text += "</ul>";
document.getElementById("content").innerHTML = text;
}
function playTrack(track)
{
document.getElementById("content").innerHTML = "This has worked";
}
It's not liking me passing the track object to the function playTrack (a simple function for now that just displays some text). I get the error "Uncaught SyntaxError: Unexpected identifier"
If I pass in track.id (or any other property), it all works fine which I don't understand.
Thanks for any help,
Mister B.
Send JSON Data from the Client SideUse JSON. stringify() to convert the JavaScript object into a JSON string. Send the URL-encoded JSON string to the server as part of the HTTP Request. This can be done using the HEAD, GET, or POST method by assigning the JSON string to a variable.
'@' is just a string like any other. In JavaScript, you can access it with result['@'] Also note that the input is not valid JSON, as it is missing quotes around many dictionary keys and Object , uses single instead of double quotes and ends with a comma.
JavaScript Objects VS JSON Though the syntax of JSON is similar to the JavaScript object, JSON is different from JavaScript objects. The key in key/value pair should be in double quotes. The key in key/value pair can be without double quotes. JSON cannot contain functions.
Yes, you can. There are tons of ways to do it. var tmpFunc = new Function(codeToRun); tmpFunc(); Whether it was JSON at any stage should be irrelevant.
You cannot pass an object like this. track
is getting converted to a string and then your playTrack
function call fails because the syntax is wrong. It'll be rendered (something like onclick=playTrack([Object object])
which clearly isn't valid JavaScript). What's wrong with just passing the track.id since you know that works?
The @alpian and @Jim is right, you need convert the object to json string, you can use http://www.json.org/js.html to this.
...
text += "<ul><li><a href=\"#\" onclick=\"playTrack('" + JSON.stringify(track) + "');return false;\">Play</a></li>"
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With