我想在不重新加载页面的情况下更改<audio>的值

时间:2016-01-02 11:38:05

标签: javascript jquery ruby-on-rails audio

我使用rails 4和javascript作为个人网络应用。这就是问题所在: 当我点击<audio>时,我想随机更改<button>的值。 要生成<audio> i的路径,请使用返回数据库中声音值的ruby函数。我想要做的是点击<button>,每次我点击它<audio>更改的值,而不重新加载页面。 以下是示例:

<button> Click me!</button>
<audio><source src="<%= $soundpath %>"></audio>
/* I click on the button and the sound path into src="" should change everytime i click on the button without reloading the page*/
<audio><source src="<%= $soundpath %>" <--[this should be different from the previus one]></audio>

1 个答案:

答案 0 :(得分:0)

使用jquery的AJAX函数请求一个URL,该URL将响应文本以将src设置为:

在您的javascript文件中:

$("button").click(function() {
  $.get( "/sounds/next_source", function( data ) {
    $( "audio" ).attr( "src", data );
  });
}

然后确保为此操作设置了路由,然后在控制器中实现它:

def next_source
    @src = Sound.last.url

  respond_to do |format|
    format.html {render :plain => @src }
  end
end