【发布时间】:2015-07-17 13:12:53
【问题描述】:
我的主页上有一个按钮,我想触发一些 ajax,以便在按下按钮时我可以在主页上看到一个表单。这适用于我的两个按钮,但不适用于第三个,我不知道为什么?当我按下按钮时,它会重定向到 root,大概是因为我使用的是“#”。然而,这确实触发了正确的 ajax(见下文) - 我知道这一点,因为我从 ajax 成功获得控制台响应。如果我将 ajax 中的 url 更改为 controller/new,那么我会在主页中正确显示新表单。所以看起来控制器操作由于某种我不明白的原因被定向到 root
这是按钮
<div class="col-md-4">
<%= link_to image_tag("arrow.jpg"),'#', id: 'ChallengeListButton'%>
<div id="challengeListCentre"></div>
</div>
这是它触发的 ajax(在 application.js 中)
$(document).ready(function(){
$('#ChallengeListButton').click(function(e){
$.ajax({
type: 'GET',
url: "challenges/index",
success: function(response){
console.log(response)
$('#challengeListCentre').html(response);
}
})
});
});
这是控制器challenges_controller.rb
class ChallengesController < ApplicationController
before_action :set_challenge, only: [:show, :edit, :update, :destroy]
# GET /challenges
# GET /challenges.json
def index
@challenges = Challenge.all
render :layout => false
end
end
这里是观点/挑战/index.html.erb
<%= render 'index' %>
<%= link_to 'Back', challenges_path %>
和部分:
<p id="notice"><%= notice %></p>
<h1>Listing Challenges</h1>
<table>
<thead>
<tr>
<th>Pointsspend</th>
<th>Rules</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @challenges.each do |challenge| %>
<tr>
<td><%= challenge.pointsSpend %></td>
<td><%= challenge.rules %></td>
<td><%= link_to 'Show', challenge %></td>
<td><%= link_to 'Edit', edit_challenge_path(challenge) %></td>
<td><%= link_to 'Destroy', challenge, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Challenge', new_challenge_path %>
以及路线:
Rails.application.routes.draw do
resources :challenges, only: [:new, :create, :show, :index, :edit, :destroy]
resources :entries
resources :conversations, only: [:index, :show, :destroy] do
member do
post :reply
post :restore
post :mark_as_read
end
collection do
delete :empty_trash
end
end
resources :messages, only: [:new, :create]
get '/messages/new/:id', to: 'messages#new'
root to: 'users#index'
devise_for :users
get '/users/relations', to: 'users#relations'
post '/users/create', to: 'users#create'
resources :users
end
【问题讨论】:
-
控制台是否显示任何错误?
-
我已经更新了上面的问题。控制台写入响应,因此正确的 ajax 正在触发,但响应是整个根页面的 html,而不是挑战的索引,所以我认为挑战/索引操作被解释为 root?
标签: ruby-on-rails ajax ruby-on-rails-4