【问题标题】:Rails controller and javascript: don't give the desired redirect resultRails 控制器和 javascript:不提供所需的重定向结果
【发布时间】:2015-10-19 08:26:09
【问题描述】:

我网站的用户可以使用折扣券。如果此优惠券使他们有权获得 100% 的回扣,则它应该为用户更新一些值并通过一条消息重定向到根目录。但是,当前的行为是在提交优惠券/表格后,屏幕上没有任何反应;即,带有表单的页面仍然显示,没有警报消息,没有重定向等。服务器日志显示正在发生操作,但我不明白为什么屏幕上没有任何反应。有人可以请教吗?

用户提交促销代码的表单:

<%= form_for @code, method: :post, url: {action: "checkcode", :controller => 'codes', format: 'js'}, remote: true do |f| %>
  <%= f.submit "Submit Code" %>
  <%= f.text_field :code, :placeholder => "Enter code" %>
  <%= some hidden_fields %>
<% end %>

这将发布到以下 javascript 文件,该文件设置一些值并在屏幕上更新这些值。

alert('<%= @message %>');
<% if @sum %>
    $('.js-sum').val('<%= @sum%>');
    $('.js-hash').val('<%= @hash%>');
    $('.js-sum2').html('<%= number_with_precision(@sum, precision: 2) %>');
<% end %>

控制器方法如下:

def checkcode
  code = Code.active.by_code(params[:code][:name]).first
  # ... some code that checks 'code' and accordingly sets `@sum`... this works
  if @sum && @sum == 0
    @message = "Accepted"
    @organization = Organization.friendly.find(params[:id])
    if @organization.update_attributes(promo_id: code.name,
                            promo_date: Time.zone.now,
                            exp_date: @organization.check_expiration)
      flash.now[:success] = "A confirmation email is sent to you."
      redirect_to root_path
    else
      flash.now[:danger] = "Error"
    end
  end
end

服务器日志:

Started POST "/checkcode.js" 
Processing by CodesController#checkcode as JS
  Parameters: {"utf8"=>"✓", "code"=>{"code"=>"fullrebate"}, "current_sum"=>"100.0", ***, "organization_id"=>"108", "commit"=>"Submit"}
  Code Load (0.9ms)  SELECT  "codes".* FROM "codes" WHERE (expiration >= '2015-07-28') AND (code = 'fullrebate')  ORDER BY "codes"."expiration" DESC LIMIT 1
  Organization Load (0.5ms)  SELECT  "organizations".* FROM "organizations" WHERE "organizations"."tag" = $1  ORDER BY "organizations"."created_at" DESC LIMIT 1  [["tag", "108"]]
  Organization Load (0.6ms)  SELECT  "organizations".* FROM "organizations" WHERE "organizations"."id" = $1  ORDER BY "organizations"."created_at" DESC LIMIT 1  [["id", 108]]
   (0.4ms)  BEGIN
  User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."organization_id" = $1  ORDER BY "users"."username" ASC  [["organization_id", 108]]
  User Exists (0.9ms)  SELECT  1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('test23@example.com') AND "users"."id" != 235) LIMIT 1
   (1.0ms)  SELECT "users"."email" FROM "users"  ORDER BY "users"."username" ASC
  User Exists (1.0ms)  SELECT  1 AS one FROM "users" WHERE (LOWER("users"."username") = LOWER('test23') AND "users"."id" != 235) LIMIT 1
  Organization Exists (0.8ms)  SELECT  1 AS one FROM "organizations" WHERE (LOWER("organizations"."name") = LOWER('test23') AND "organizations"."id" != 108) LIMIT 1
  Organization Exists (0.7ms)  SELECT  1 AS one FROM "organizations" WHERE (LOWER("organizations"."tag") = LOWER('tes23') AND "organizations"."id" != 108) LIMIT 1
  SQL (0.6ms)  UPDATE "organizations" SET "expiration" = $1, "updated_at" = $2 WHERE "organizations"."id" = $3  [["expiration", "2020-07-31"], ["updated_at", "2015-07-28 16:10:38.906460"], ["id", 108]]
   (3.7ms)  COMMIT
Redirected to https://homepage.com/
Completed 302 Found in 241ms (ActiveRecord: 11.6ms)

Started GET "/" 
Processing by HomePagesController#home as JS
  Rendered shared/_header.html.erb (53.9ms)
  Rendered shared/_error_messages.html.erb (0.6ms)
  Rendered home_pages/home.html.erb within layouts/application (399.8ms)
  Rendered shared/_shim.html.erb (0.5ms)
  Rendered shared/_footer.html.erb (3.9ms)
Completed 200 OK in 3431ms (Views: 3421.5ms | ActiveRecord: 0.0ms)

因此,一方面服务器日志显示它正在执行控制器方法并进行重定向,但同时在屏幕上什么也没有发生(即,没有转到主页)。 Processing by HomePagesController#home as JS 这行让我觉得很奇怪。 as JS 是否可能是问题的原因以及如何解决?

【问题讨论】:

  • remote: true 发出 ajax 请求并被视为 js 。从表单标签中删除 remote: trueformat: js 并尝试如果你想要 html 请求
  • 试过 Athar,然后它确实有效。但是,在回扣低于 100% 的(更常见的)情况下,我需要 javascript/ajax。然后javascript是必要的。有没有办法解决这个问题?
  • 对不起,我没有收到你的问题。你需要 js 和 html。?
  • 是的,我两者都需要。在帖子中,我省略了控制器方法的一部分,如果仍有要支付的价格(所以如果回扣小于 100%)则执行。然后使用 ajax 来更新屏幕上显示的价格。 (并且 ajax 还显示有关是否接受优惠券的消息)。如果优惠券使用户有权获得 100% 的回扣,则实际上不需要 ajax。
  • 好的,一个表单可以处理 ajax 请求或 html 请求。你不能同时做到这两点。如果控制器以js 接收请求,它将呈现.js.erb 文件,如果html 请求它将重定向或呈现.html.erb 文件。据我所知,您需要单独的表格来处理这两个请求。

标签: javascript ruby-on-rails ruby ruby-on-rails-4 model-view-controller


【解决方案1】:

通过js请求重定向试试这个。

<% if @amount && @amount < 0.01 %> 
  $(window.location.replace("/"))
<% end %> 

alert('<%= @msg %>'); 
<% if @amount %> 
  $('.js-input-amount').val('<%= @amount%>'); 
  $('.js-input-hash').val('<%= @hash%>'); 
  $('.js-text-amount').html('<%= number_with_precision(@amount, precision: 2) %>'); 
<% end %>

【讨论】:

    【解决方案2】:

    这很丑陋,但它有效,将你的操作代码更改为:

    def checkcode
      # some code here    
      render js: "window.location = '#{root_path}'"
      # some code here
    end
    

    这会直接在客户端渲染js 代码,并将window 位置更改为预期的url(在这种情况下为root_path)。

    【讨论】:

      【解决方案3】:

      你应该使用

       redirect_to action: :index
      

      redirect_to '/'
      

      而不是

      redirect_to root_path
      

      如果这是异步帖子的问题,您可以尝试使用类似的东西

      respond_to do |format|
        format.js { :location => path_to_controller_method_url(argument) }
      end
      

      在您的控制器中。

      【讨论】:

      • 不幸的是,这没有什么区别:在服务器日志中它显示Redirected to ...,然后指定重定向到的任何内容(我也尝试了其他路径)。但在屏幕上什么都没有发生。我认为这可能与服务器中Processing by HomePagesController#home as JS 的内容有关。为什么as JS 以及如何处理它?
      • 我编辑了我的答案,提出了异步帖子的建议。
      猜你喜欢
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      相关资源
      最近更新 更多