【问题标题】:How can I redirect a user back from a page with no html/view?如何将用户从没有 html/view 的页面重定向回来?
【发布时间】:2016-12-21 03:15:30
【问题描述】:

我正在做一个挑战,它使用 Sinatra 和 Javascript 以及一个 JSON 文件作为数据库(各种)并且遇到了一个让我发疯了两天的障碍。问题是我希望能够在成功提交后将用户与/homepage 表单保持在同一页面上(或自动将它们重定向回来),并从那里通知他们成功提交。实际发生的是,一旦我提交表单,用户就会被重定向到 (POST) '/' 路由(并停留在那里) - 但是没有与该端点关联的视图。显示的是服务器端消息。

这里是 config.ru:

##QUERY THE USERS LIST
get "/" do
  protected!
  File.open("./test-users.json").read
end

##ADD A NEW USER
post "/" do
  protected!
  param :name, String, required: true
  param :email, String, required: true, format: /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/

  contents = File.open("./test-users.json").read
  parsed_contents = JSON.parse(contents)
  File.delete("./test-users.json")
  parsed_contents["guests"] << {"email" => params["email"], "name" => params["name"]}
  File.open("./test-users.json", "w+") do |f|
    f.puts JSON.pretty_generate(parsed_contents)
  end

  "#{params['name']} now signed up with #{params['email']}"
end

现在,我不允许修改该文件或(这会容易得多!)。这是我的表格:

  <div class="sidebar-left col-xs-12 col-sm-4">
    <form action="/" method="POST" id="registrantForm">
      <h1>Please Register</h1>
      <input type="text" name="name" id="register-name" placeholder="username" required>
      <input type="email" name="email" id="register-email" placeholder="email" required>
      <input type="submit" value="Submit">
      <div id="form-error" class="error"></div> 
    </form>
  </div>

这是我尝试过的一些事情,

  • 检测当前window.location,如果是'/',则重定向回来。这不起作用,因为一旦您在 '/' 路线上 - 您不再在 html 页面上,因此 javascript 不起作用。

  • 玩弄 onbeforeunload,但这不起作用,因为我无权访问目标路由,并意识到即使我这样做了,如果我之前重定向远离 '/',我会阻止提交提交完成。

  • 将表单的提交从 html 中拉到 JS 中以尝试在提交后控制路由(使用 onload 事件),但是我无法获取要发布的数据或发送参数作为查询字符串或字符串化对象:

function submit(emailInput, nameInput){
  var params = {
    email: emailInput,
    name: nameInput
  };
  request.open("POST", "http://localhost:9292", true);
  request.send(JSON.stringify(params));
  request.onload(function(){
    window.location.assign('http://localhost:9292/homepage');
  });
}

或者不使用request.send() 发送参数,因为无论如何它似乎是从 url 的搜索查询中获取它。两者都会导致页面在提交时重新加载,而不会重定向到'\',但也不会保存数据。

如何在成功提交表单数据的同时将用户重定向回/homepage 路由?在这个设置中这可能吗?

【问题讨论】:

  • 所以你根本不允许更改 ruby​​ 代码?
  • 没有。无法根据说明更改该代码。我现在认为这是未能从服务器文件重定向的疏忽,我已经提交了两个版本的挑战 - 一个我没有重定向我只是把它留在那里并解决它,另一个我确实添加了一个重定向到文件。但在这种情况下 - 我可以从客户端以某种方式重定向吗?
  • 可能最简单的方法是用 js 替换表单操作,然后用 js 提交值 - 这样就不会发生重定向
  • 我试过了,它不会提交。也许是因为我没有正确发送参数。身份证。似乎它们来自 url 的查询字符串......但它不起作用 - 所以我重新创建了查询字符串,并发送了它。没有运气。我将它们作为对象发送,包括 JSONstringified 和常规对象,没有运气。数据将被提交到 JSON 文件(充当数据库)。最终我做了两个版本,一个是我重定向服务器端的版本(如果这是他们的疏忽),另一个我没有,只是处理重定向。没有通过挑战:(
  • 在“我尝试过的事情”下,我实际上说我尝试了所有这些;)

标签: javascript json sinatra http-redirect


【解决方案1】:

可能最简单的方法是用 js 替换表单操作,然后用 js 提交值 - 这样就不会发生重定向

这正是它的工作原理。所以我构建了一些示例代码来证明并解释它。 (提示:我使用 jQuery 只是为了方便你可以在纯 js 中执行此操作)

<script type="text/javascript">
    $( document ).ready(function() {
        // submit the from values with js 
        // and clean the input fields 
        // but not submit the form normally
        // that's why false is returned
        $('form').submit(function() {
            // get your form data in a standard URL-encoded notation
            // standard URL-encoded notation
            var data = $('form').serialize();

            // post your data with ajax to the server
            // https://api.jquery.com/jQuery.post/
            // here you would add your on success function
            // to display a message to the user or whatever else
            $.post('/', data);

            // retuning false here prevents the form to get posted
            // https://api.jquery.com/submit/
            return false;
        });
    });
</script>

附注 ruby​​ 代码有很大的改进潜力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2016-03-06
    • 2012-08-09
    • 2012-01-02
    • 2011-01-14
    • 2015-08-15
    • 2011-07-21
    相关资源
    最近更新 更多