jQuery how to generate code inside code?
my question might be a bit confusing, but here is what i would like to do. i have a script:
<script>
...some script here...
var audioPlaylist = new Playlist("2", [
{
name:"Lismore",
mp3:"http://example.com/song.mp3"
},
{
name:"The Separation",
mp3:"http://example.com/song1.mp3"
}
])
</script>
what i would like to do is to generate that script dynamically using $.get.JSON
var audioPlaylist = new Playlist("2", [
$.getJSON('http开发者_StackOverflow中文版://www.example.com/users', function(data) {
$.each(data, function(i,item) {
document.write(name: ''item.fname'',)
document.write(mp3: "http://example.com/"''+item.song_id+''".mp3")
}):
});
])
inside the <script>
is this possible? i've tried the script and it fails.
It would be possible to generate code dynamically to do that, but there is no reason to do that.
Just use the map
method to convert the array of data that you get from the AJAX call into the form that you need for the Playlist
object:
$.getJSON('http://www.example.com/users', function(data) {
var items = $.map(data, function(item) {
return { name: item.fname, mp3: "http://example.com/" + item.song_id + ".mp3" };
});
var audioPlaylist = new Playlist("2", items);
});
Try this:
//Note: getJSON call is asynchronous, unless the ajaxSettings are modified to make it synchronous and hence audioPlaylist variable is assigned a value only after the callback of getJSON is completed.
var audioPlaylist = null;
$.getJSON('http://www.example.com/users', function(data) {
var playData = [];
$.each(data, function(i,item) {
playData.push({
name:item.fname,
mp3: "http://example.com/" + item.song_id + ".mp3"
});
audioPlaylist = new Playlist("2", playData);
alert(audioPlaylist);
});
});
The above answer is best if you're trying to update the data. If you actually want to write scripts to the page, first get the script text assembled and then do something simple like:
$('body').append("<script type='text/javascript'>alert('hello world');<\/script>");
<script>
//Song Object
function Song(name, mp3){
this.name = name;
this.mp3 = mp3;
}
//Create array of Song objects
var songs = new Array();
//Populate it from the AJAX call
$.getJSON('http://www.example.com/users', function(data) {
$.each(data, function(i,item) {
songs.push(new Song(item.fname, "http://example.com/" + item.song_id + ".mp3"));
}):
});
//build the Playlist Object
var audioPlaylist = new Playlist("2",songs);
</script>
精彩评论