【问题标题】:How to execute a rails command with sweet alert 2?如何使用甜蜜警报 2 执行 rails 命令?
【发布时间】:2021-05-07 11:03:59
【问题描述】:

我有以下sweet alert 2 消息:

<button onclick='
    Swal.fire({
      title: "Select a page you want to be redirected:",
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: "Home",
      denyButtonText: "About",
    }).then((result) => {
      /* Read more about isConfirmed, isDenied below */
      if (result.isConfirmed) {
        Swal.fire("Saved!", "", "success");
      } else if (result.isDenied) {
        Swal.fire("Changes are not saved!", "", "info");
      }
    });
'>SHOW SWEET ALERT</button>

设计看起来还不错,但问题是我无法执行.erb 命令,而是显示另一条甜蜜的警报消息!

例如,如果我将上面的代码更改为以下代码,它会搞砸一切,我不知道是什么原因造成的!:

<button onclick='
    Swal.fire({
      title: "Select a page you want to be redirected:",
      showDenyButton: true,
      showCancelButton: true,
      confirmButtonText: "Home",
      denyButtonText: "About",
    }).then((result) => {
      /* Read more about isConfirmed, isDenied below */
      if (result.isConfirmed) {
        <%= link_to "Home Page", root_path, class:"navbar-brand" %>
      } else if (result.isDenied) {
        <%= link_to "About Page", home_about_path, class:"nav-link" %>
      }
    });
'>SHOW SWEET ALERT</button>

代码片段 2 将给出以下错误:Uncaught SyntaxError: Unexpected token '&lt;'

第一个sn-p的图片示例:

第二个sn-p的图片示例:

【问题讨论】:

    标签: javascript html ruby-on-rails erb sweetalert2


    【解决方案1】:

    实际上这是预期的行为。

    正如您在第二个屏幕截图中看到的那样,ERB 解析器在您的 JavaScript 代码中生成了正确的锚标记,从而导致了 SyntaxError。 (你不能在 JavaScript 中使用 HTML!当然,除非它们在字符串引号周围。)

    你想要做的是这样的:

    <button onclick='
        Swal.fire({
          title: "Select a page you want to be redirected:",
          showDenyButton: true,
          showCancelButton: true,
          confirmButtonText: "Home",
          denyButtonText: "About",
        }).then((result) => {
          /* Read more about isConfirmed, isDenied below */
          if (result.isConfirmed) {        
            location.pathname = "<%= root_path %>"
          } else if (result.isDenied) {
            location.pathname = "<%= home_about_path %>"
          }
        });
    '>SHOW SWEET ALERT</button>
    

    "location.pathname = x" 将引导您到相对路径。

    服务器的 ERB 解析器会将 root_path 和 home_about_path 变量替换为您要查找的路径。

    【讨论】:

    • 非常感谢@KeweiJiang 的回答!不过我还有最后一个问题!我如何确定用于此的方法?例如:我想使用DELETE 方法重定向到friends_path!否则会进入好友索引,即显示好友列表页面!
    • 如果要发出删除 HTTP 请求,则需要发出 AJAX 请求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多