Rails AJAX错误 [英] Rails AJAX error

查看:44
本文介绍了Rails AJAX错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

<p id="click">Click here</p> 

在控制器中:

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("<%= escape_javascript(render(@person))%>");  

_persons.html.erb

<h3><%= @person.name %></h3>  

index.html.erb

    <div id="show">
      <%= render @person %>
    </div>    

路线

获取'/index',以:"main#index"将'/index'放到:"main#index"

get '/index', to: "main#index" put '/index', to: "main#index"

现在,当我执行索引操作时,我会得到

Now when I got to the index action I get

找不到ID为nil的人

Person not found with id = nil

在加载页面之前.为什么@person实例变量直接执行?我什至无法进入索引页面.Rails Ajax如何工作?怎么知道 @person 变量要通过Ajax执行?

Before even the page is loaded. Why is the @person instance variable executed directly? I'm not even able to get to the index page. How does rails ajax work? How does it know the @person variable is to be executed via ajax?

推荐答案

这不是Ajax错误.这是正常的Rails错误.您正在执行:

It's not an Ajax error. It's a normal Rails error. You're doing:

@person=Person.where(id: params[:id])

但是在索引操作中,没有 params [:id] ,所以您实际上在做的是:

But in the the index action there is no params[:id], so what you're actually doing is:

@person = Person.where(id: nil)

这就是错误所在.

主要问题是您试图在一个动作中做两件事.您应该对Ajax调用进行单独的操作:

The main problem is that you're trying to do two things in one action. You should make a separate action for the Ajax call:

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 操作添加一条路线,但这是个主意.

Something like this. You'll need to add a route for the ajax_call action, but this is the idea.

这篇关于Rails AJAX错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆