Ruby on rails Ajax调用显示404错误

时间:2014-05-28 11:08:35

标签: ruby-on-rails ruby ajax

我正在制作和ajax调用以击中控制器,但它显示404错误:

我的控制器方法如下:

def get_user_time
    if(params[:user])
        @user_time_checks = UserTimeCheck.where(:user_id => params[:user])
    end
end

我的路线就像:

post "user_time_checks/get_user_time"

我的ajax脚本就像:

 function get_user_time(id) {
     var user_id = id;   
     if(user_id != ''){       
        $.ajax({
          url:"get_user_time?user="+user_id,
          type:"POST",
          success: function(time){
            console.log(time);
          },error: function(xhr,response){
            console.log("Error code is "+xhr.status+" and the error is "+response);
          }
        });
      }
  }

2 个答案:

答案 0 :(得分:1)

试试这个:

$.ajax({
  url:"user_time_checks/get_user_time",
  type:"POST",
  data: {
    user: user_id 
  },  
  success: function(time){
    console.log(time);
  },error: function(xhr,response){
    console.log("Error code is "+xhr.status+" and the error is "+response);
  }
});

还要确保您确实需要执行POST方法,并且rails路由不需要特定的参数,例如:user_id。基本上检查

的输出
rake routes | grep get_user_time

答案 1 :(得分:0)

您的路线应该是:

post "user_time_checks/get_user_time" => "user_time_checks#get_user_time"

此外,由于请求的目的是get某些数据,因此您应该将其设为GET请求。所以:

function get_user_time(id) {
    var user_id = id;
    if(user_id != ''){
        $.get("get_user_time",
                    {user: user_id})
        .success(function(time) {
            console.log(time);
        })
        .error(function(xhr,response){
            console.log("Error code is "+xhr.status+" and the error is "+response);
        });
    }
}

最后,也许你应该告诉控制器能够repond_to json:

def get_user_time
    if(params[:user])
        @user_time_checks = UserTimeCheck.where(:user_id => params[:user])
        respond_to do |format|
            format.html # The .html response
            format.json { render :json => @user_time_checks }
        end
    end
end