【问题标题】:Making an ajax call on a link click to update the link itself (Ruby on Rails)对链接进行 ajax 调用单击以更新链接本身(Ruby on Rails)
【发布时间】:2021-09-21 23:38:43
【问题描述】:

我正在开发的应用程序有一个更新程序页面,单击链接将提示下载最新版本的 iOS 应用程序。但是,当从 webclip 打开更新程序页面时,webclip 可能不是最新版本。我的解决方案是运行 ajax 查询来检索最新版本。

这里是查询:

$('.download-link').click(function(event) {
    $.ajax({
        url: "/updater",
        type: "GET",
        success: function(result){
        }
    })
})

这是控制器中的方法:

def update
  @version = AppVersion.find_by(app_type: "AppType", is_active: true)
end

这里是 updater.html.erb 文件中的相关链接:

<a class="download-link" href="itms-services://?action=download-manifest&url=<%= @version.link_to_stable_build %>">

我对 ajax 不是很熟悉,也不完全确定从这里到哪里去实际确保调用该方法来更新 updater.html.erb 文件中的链接。

【问题讨论】:

    标签: ruby-on-rails ajax


    【解决方案1】:

    这里不需要视图。只需在 Location 标头中返回带有 URL 的标头响应:

    def update
      version = AppVersion.find_by(app_type: "AppType", is_active: true)
      url = "itms-services://?action=download-manifest&url=" + version.link_to_stable_build
      render head: :ok, 
             location: url
    end
    

    然后只需更新 javascript 处理程序中的 DOM:

    // delegation makes this compatible with turbolinks
    $(document).on('click', '.download-link', function(event) {
      let link = $(this);  
      // shorthand for $.ajax ....
      $.get("/updater", function(data, textStatus, jqXHR) {
        let uri = jqXHR.getResponseHeader('Location');
        link.attr('href', uri);
        // or if you want to promt a download 
        // window.location = uri;
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 1970-01-01
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      相关资源
      最近更新 更多