Problem passing a JSON object to a function
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 开发者_StackOverflowobject = 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.
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>"
...
When creating the "playTrack" onclick event, you are using the track variable in the wrong way. "track" is an object, and using it as a string will be [Object object]. So in your "html" you'll have something like onclick="playtrack([Object object])" and this is syntactically wrong.
I'd strongly suggest the use of JSON.parse()
instead of eval
. Instead of building your list entries as text I'd make them as DOM objects with document.createElement()
and add the click handlers as addEventListener
, that way you wouldn't have the need to try to include your JS objects as text in the HTML stream.
精彩评论