如何将params传递给Rails控制器方法然后使用JQuery / AJAX返回值?

时间:2017-06-01 20:49:25

标签: javascript jquery ruby-on-rails ruby ajax

我使用click函数首先获取数组/位置,然后通过AJAX调用将其发布到控制器方法。然后我想让方法返回一个布尔值来启用jquery函数中的addClass。控制台始终丢失500服务器错误。

这是.js文件:

   $(document).ready(function(){
     $("#backboard").on("click", "div", function(e){
       $("#backboard div").removeClass("selected");
       var val = $(this).data('val');
     $.ajax ({
        type: 'POST',
        url: "https://localhost:3000/chess/:pos",
        data: {pos: {value: val}},
        success: function(d){
          if(d === true){
            $(this).addClass("selected").append("<p>"+val+"<p>");
          }
        }
      });
    });
  });

这是controller.rb文件:

 class ChessController < ApplicationController
    include ChessHelper

    def new
    @select = false
    @game = Game.new("white", "ARSEFACE!!!")
    @arr = @game.board
    @cpu = @game.cpuName
    @player = @game.playerName



   end

   def select
      pos = params[:pos]
     a = pos[0]
     b = pos[1]

     if(@arr[a][b][0]===@color)
        @select = !@select
     end

     respond_to do |format|
       format.json { render json: @select }
      end
    end
  end

这是config / routes.rb:

   get '/chess', to: 'chess#new'
   post '/chess/:pos' => 'chess#select' 

我知道我可能会遗漏一些非常明显的东西,但任何帮助都会受到赞赏!

PS和从变量中获取数据的val变量实际上有一个值。我试图将该值传递给控制器​​以返回true或false,并且一旦我解决了这个基本问题,最终将成为验证函数。

1 个答案:

答案 0 :(得分:2)

url: "https://localhost:3000/chess/:pos",不会被插值,除非我完全遗漏了某些内容。

使用post '/chess/:pos' => 'chess#select',您可以告诉Rails(特定于其路由器)在:pos位置的请求路径中查找参数,并在找到它时设置值params散列(params[:pos])到路径中:pos的字符串。

jQuery对Rails&#39;一无所知。路由器。也没有Javascript。

要了解我的意思,请将其添加到您的routes.rb文件中:

get '/:cookies/and/:cream' => 'application#test'

application_controller.rb中添加以下内容:

def test
  render :text => "I love me some #{params[:cookies]} with my #{params[:cream]}"
end

然后点击http://localhost:3000/chocolate-chip/and/milk

应该阅读&#34;我爱我一些巧克力片和我的牛奶&#34;

现在,假设您的其他代码没问题,

$("#backboard").on("click", "div", function(e){
       $("#backboard div").removeClass("selected");
       var val = $(this).data('val');
     $.ajax ({
        type: 'POST',
        url: "http://localhost:3000/chess/" + val,
        success: function(d){
          if(d === true){
            $(this).addClass("selected").append("<p>"+val+"<p>");
          }
        }
      });

应该这样做。无需在ajax函数中传递任何额外的data

另外,不要在开发中使用HTTPS。它只会让你头痛。

相关问题