【问题标题】:I'd like to change the value of an <audio> without reloading the page我想在不重新加载页面的情况下更改 <audio> 的值
【发布时间】:2016-01-02 11:38:05
【问题描述】:

我正在为个人网络应用程序使用 rails 4 和 javascript。这是问题所在: 当我点击&lt;button&gt; 时,我想随机更改&lt;audio&gt; 的值。 为了生成&lt;audio&gt; 的路径,我使用了一个ruby 函数,它从数据库中返回声音的值。我想做的是单击&lt;button&gt;,每次单击它时,&lt;audio&gt; 的值都会更改而无需重新加载页面。 这是和示例:

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

【问题讨论】:

    标签: javascript jquery ruby-on-rails audio


    【解决方案1】:

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

    【讨论】:

    • 好的抱歉,现在我将更改我的请求 XD 我想从控制器调用 ruby​​ 函数到 javascript 函数中,例如 function f1(){ if(s==true) /* 这里是我想从控制器调用 ruby​​ 函数 */ } 而无需在点击时重新加载页面
    • 我的回答没有重新加载页面。它对要设置 src 的新字符串发出异步请求。如果您想因为 if 语句而导致 AJAX 请求发生,请将第 1 行更改为您的 if 语句。
    猜你喜欢
    • 2020-10-04
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 2020-04-20
    • 2016-10-28
    • 2013-06-21
    • 2012-05-26
    相关资源
    最近更新 更多