【问题标题】:jQuery how to generate code inside code?jQuery如何在代码中生成代码?
【发布时间】:2011-04-11 18:48:35
【问题描述】:

我的问题可能有点令人困惑,但这是我想做的。 我有一个脚本:

<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")
}):
});
])

在&lt;script&gt;里面

这可能吗?我已经尝试了脚本,但它失败了。

【问题讨论】:

  • 不要真的理解你的问题..你需要从服务器接收播放列表内容吗?

标签: jquery json load document.write


【解决方案1】:

可以动态生成代码来执行此操作,但没有理由这样做。

只需使用map 方法将从AJAX 调用获得的数据数组转换为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);
});

【讨论】:

  • 看起来它正在工作..我收到一些undefined 错误,但我确定这是一个 JSON 问题。谢谢大家
【解决方案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);
    });
 });

【讨论】:

    【解决方案3】:

    如果您尝试更新数据,上述答案是最好的。如果你真的想在页面上写脚本,首先把脚本文本组装起来,然后做一些简单的事情,比如:

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

    【讨论】:

      【解决方案4】:
      <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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-15
        • 2010-12-29
        • 2012-10-03
        • 2012-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多