简体   繁体   English

Ruby on Rails Ajax调用显示404错误

[英]Ruby on rails Ajax call showing 404 error

I am making and ajax call to hit the controller but it is showing the 404 error: 我正在进行ajax调用以击中控制器,但它显示404错误:

My controller method is like: 我的控制器方法是这样的:

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

And my route for this is like: 我的路线是这样的:

post "user_time_checks/get_user_time"

And my ajax script is like: 我的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);
          }
        });
      }
  }

Try this: 尝试这个:

$.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);
  }
});

Also make sure you really need to do POST method and that rails route does not require specific paramater like :user_id. 还要确保您确实需要执行POST方法,并且rails路由不需要诸如:user_id之类的特定参数。 Basically check the output from 基本上检查输出

rake routes | grep get_user_time

Your route should be: 您的路线应为:

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

Also, since the purpose of the request is to get some data, you should make it a GET request instead. 另外,由于请求的目的是get一些数据,因此您应该将其设为GET请求。 So: 所以:

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);
        });
    }
}

Lastly, maybe you should tell the controller to be able to repond_to json: 最后,也许您应该告诉控制器能够对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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM