2011-04-11 18 views
0

我的问题可能有点混乱,但这是我想要做的。 我有一个脚本:jQuery如何在代码中生成代码?

<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> 

我想要做的是动态生成使用$ .get.JSON

var audioPlaylist = new Playlist("2", [ 
$.getJSON('http://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") 
}): 
}); 
]) 

<script>

内这可能是脚本?我试过这个脚本,但它失败了。

+0

唐没有真正undrestand你的问题..你需要从收到服务器播放列表的内容? – 2011-04-11 18:55:29

回答

3

这样做可以动态生成代码,但没有理由这样做。

只需使用map方法将数据的数组,你从A​​JAX调用进入,你需要为Playlist对象的形式转换:

$.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); 
}); 
+0

+1。我应该赶上使用jQuery的地图功能。 – Chandu 2011-04-11 19:01:23

+0

看起来像它的工作..我得到一些'未定义的错误,但我敢肯定,这是一个JSON问题。多谢你们 – Patrioticcow 2011-04-11 19:16:19

2

尝试这种情况:

//注:的getJSON呼叫是异步的,除非ajaxSettings被修改,以使其同步,因此audioPlaylist变量分配的getJSON回调完成后才的值。

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); 
    }); 
}); 
0
<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> 
0

以上的回答是最好的,如果你正在尝试更新数据。如果你真的想编写脚本的页面,第一个拿到剧本文字组装,然后不喜欢简单的东西:

$('body').append("<script type='text/javascript'>alert('hello world');<\/script>");