[英]Unable to call controller method through ajax in rails
我已經嘗試了所有的谷歌搜索技能,但是還無法解決問題。
我正在嘗試使用ajax從jquery向控制器方法發送參數。 一旦方法被調用,它將呈現其各自的視圖頁面。 但是它甚至沒有輸入ajax代碼來調用控制器方法(通過檢查)。 我想我做的事情確實很愚蠢,但無法弄清楚,請幫幫我。
我的控制器方法代碼:
def profile
@prof = User.where(:id => params[:id])
end
我的.js文件
$(document).ready(function(){
$('.table tr').click(function(){
$.ajax({
url: "users/profile",
type: "POST",
data: {id: $(this).attr('id')},
success: function (data) {
alert(data);
}
});
});
});
我的路線文件:
resources :users, :only => [:new, :create, :index,:profile]
match 'users/profile' => 'users#profile', :as => :profile
在您的routes.rb中嘗試一下
resources :users, :only => [:new, :create, :index]
get 'users/profile/:id' => 'users#profile', :as => :profile
並更改您的js方法:
$(document).ready(function(){
$('.table tr').click(function(){
$.ajax({
url: "/users/profile/" + $(this).attr('id'),
type: "GET",
success: function (data) {
alert(data);
}
});
});
});
並且您的方法應序列化為json,如下所示:
def profile
@prof = User.where(:id => params[:id])
respond_to do |format|
format.json { render :json => @proof }
end
end
更改您的js方法:
$(document).ready(function(){
$('.tr_class').click(function(){
$.ajax({
url: "/users/profile?id="+$(this).attr('id'),
type: "GET",
success: function (data) {
alert(data);
}
});
});
});
並且您的方法應序列化為json,如下所示:
def profile
@prof = User.where(:id => params[:id])
respond_to do |format|
format.json { render :json => @proof }
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.