Rails AJAX错误
我有:
Click here
在控制器中:
def index @all=Person.all @person=Person.where(id: params[:id]) respond_to do |format| format.html format.js end end
和:
$('#click').on('click',function(){ $.ajax({ type: "POST", data: 'id='+id, url: "/index" }); }
index.js.erb的
$("#show").html("");
_persons.html.erb
index.html.erb
路线
get’/ index’,to:“main #index”put’/ index’,to:“main #index”
现在,当我得到索引动作时,我得到了
找不到id = nil的人
甚至在加载页面之前。 为什么@person实例变量直接执行? 我甚至无法进入索引页面。 rails ajax如何工作? 怎么知道@person变量是通过ajax执行的?
这不是Ajax错误。 这是一个正常的Rails错误。 你在做:
@person=Person.where(id: params[:id])
但是在索引操作中没有params[:id]
,所以你实际做的是:
@person = Person.where(id: nil)
这就是错误所在。
主要问题是你试图在一个动作中做两件事。 您应该为Ajax调用单独执行操作:
def index @all = Person.all end def ajax_call @person = Person.where(id: params[:id]) respond_to do |format| format.html format.js end end $('#click').on('click',function(){ $.ajax({ type: "POST", data: 'id='+id, url: "/ajax_call" }); }
像这样的东西。 您需要为ajax_call
操作添加路由,但这是个主意。