【问题标题】:Unable to give url to function in jquery无法提供 url 以在 jquery 中运行
【发布时间】:2018-06-22 12:09:07
【问题描述】:

<script type="text/javascript">
    var url = "http://localhost:8000/api/songs/rock";
    var song;
    var artist;
    var genre;
    var album;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json', // added data type
        success: function(res) {
            console.log(res);
            song = res.song;
            artist = res.artist.name;
            album = res.album.albumb_title;
            genre = res.genre.name;
            console.log(song);
            console.log(artist);
            console.log(genre);
            console.log(album);
        }
    });

    $(document).ready(function(){
      $("#jquery_jplayer_1").jPlayer({
        ready: function () {

          $(this).jPlayer("setMedia", {
            mp3: song,
          });

        },

        swfPath: "http://jplayer.org/latest/js",

        supplied: "mp3",
      });

    });

所以我使用 ajax 来调用我的本地 API 并尝试将我的响应发送到 jplayer 函数。我无法弄清楚如何给“mp3”一个网址并从中播放一首歌。

【问题讨论】:

  • 据我了解的问题,您需要将 jplayer 代码放在一个函数中,并在 ajax 调用函数的响应中调用它,并将歌曲作为参数传递给该函数...

标签: javascript jquery json api jplayer


【解决方案1】:

因为您在将 song 初始化为响应值之前使用它。

阅读更多关于 asyn here

一个快速的解决方案是将您的歌曲播放脚本包装在一个函数中,然后在 ajax 请求的成功回调中调用该函数

<script type="text/javascript">
    var url = "http://localhost:8000/api/songs/rock";
    var song;
    var artist;
    var genre;
    var album;
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json', // added data type
        success: function(res) {
            console.log(res);
            song = res.song;
            artist = res.artist.name;
            album = res.album.albumb_title;
            genre = res.genre.name;
            console.log(song);
            console.log(artist);
            console.log(genre);
            console.log(album);
            playSong(song)
        }
    });

     
      function playSong(song){
       $("#jquery_jplayer_1").jPlayer({
        ready: function () {

          $(this).jPlayer("setMedia", {
            mp3: song,
          });

        },

        swfPath: "http://jplayer.org/latest/js",

        supplied: "mp3",
      });
      }
     

【讨论】:

    【解决方案2】:

    在ajax准备好之后再调用jplayer函数。

    $(document).ready(function(){
         $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json', // added data type
                success: function(res) {
                     $("#jquery_jplayer_1").jPlayer({
                     ..........
                }
            });
    

    为了说明,我跳过了一些代码。

    首先当文档准备好时调用ajax,当ajax完成时调用jPlayer函数。

    【讨论】:

      猜你喜欢
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 2014-10-08
      • 2015-04-08
      • 2011-08-13
      • 1970-01-01
      相关资源
      最近更新 更多