繁体   English   中英

如何在Rails控制器中响应AJAX POST请求

[英]How to respond to AJAX POST request in rails controller

我正在尝试让我的Google chrome扩展程序使用Ajax将数据发送到Rails网站上的ruby上,并且无法弄清这里发生的情况:

我看到我的Rails服务器已接收到我正在发送的数据(两个数组),但是有一个404? 然后我有关于用户ID的错误?

Started POST "/add_service" for 127.0.0.1 at 2014-01-24 00:34:37 +0800
Processing by UsersController#add_service as HTML
  Parameters: {"urlArray2"=>["0.0.0.0", "item.jd.com", "stackoverflow.com", "www.google.com.hk"], "countArray2"=>["3670", "20", "2", "2"]}
  User Load (11.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
Completed 404 Not Found in 13ms

ActiveRecord::RecordNotFound - Couldn't find User without an ID:
...
...

这是我的Chrome扩展程序中的Ajax:

jQuery.ajax({
type: "POST",
dataType: "JSON",    
    url: "http://0.0.0.0:3000/add_service",
    data: ({'urlArray2':urlArray2,'countArray2':countArray2}),
    success: function(){
        //alert("Web services loaded into ConsultFred.");
    }
});

这是我的用户控制器:

skip_before_filter :verify_authenticity_token, :only => [:add_service]
...
...
def add_service
  logger.debug "This is working..."
  #@user = current_user
  #@user.sitearray = params[:urlArray2]
  repsond_to do |format|
     format.html { redirect_to root_url }
     format.json { redirect_to root_url }
  end
end

我的routes.rb(编辑:添加了更多信息):

  resources :users, :only => [:index, :show, :edit, :update ] do
    post :share_to_linkedin, on: :member
  end

  post 'add_service', to: 'users#add_service'

[编辑1月24日]

现在看一下AJAX响应,实际上是参数存在问题,没有提供user.id号:

ActiveRecord::RecordNotFound at /add_service
============================================
> Couldn't find User without an ID

但是我怎么能发送呢? Ajax请求是Chrome扩展程序的外部请求吗?

我认为这些行为您把握关键:

User Load (11.4ms)  SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 1]]
  Completed 404 Not Found in 13ms

ActiveRecord::RecordNotFound - Couldn't find User without an ID

看来您没有正确将参数传递给查询。 $1应该已经作为实际值传递到SQL语句。

暂无
暂无

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

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