Ajax in rails returns alway error callback

2019-09-17 03:33发布

I posted question recentry as same how to use local or instance variable inruby codein coffeescript in haml templ

Getting helpful comment, I'm trying to pass param to controller in ajax but it always returns error callback I can't not find the reason.

Here is my code.

.html.haml

:coffee
$('input#field').change ->
    $.ajax
        url: '/posts/gaga'
        type: "GET"
        dataType: "json"
        data: { code: $('input#field').val() }
        error: (jqXHR, textStatus, errorThrown) ->
            alert "error"
        success: (data, textStatus, jqXHR) ->
            alert "success"

routes.rb

get 'posts/gaga'

posts_controller.rb

def gaga
    @model = Model.new
    render nothing: true
end

Does anyone know what's wrong my code?

Thanks in advance.

1条回答
Juvenile、少年°
2楼-- · 2019-09-17 03:57

I think your route is incorrect. It should be formatted like this at least:

get "posts/gaga", to: "posts#gaga"

However this might be more what you want if you already have a resources :posts in your routes.rb:

resource :posts do
  collection do
    get :gaga
  end
end

Because then you can avoid repeating get "posts/..." if you plan on adding more custom actions.

查看更多
登录 后发表回答