使用rails response_to格式化js以获取Ajax请求

时间:2016-10-27 21:57:48

标签: jquery ruby-on-rails ajax

我正在尝试制作一个Ajax请求,在单击单选按钮时进行更新而不重新加载整个页面。

在我的控制器中更新操作定义。在Rails文档中,这部分确实没有那么多信息。

 def update
    if @rsvp.update(rsvp_params)
      respond_to do |format|
        format.js
      end
    end
  end

update.js.erb,不确定这段代码是否有效,但由于Rails甚至找不到它,我无法测试它:

$(document).on('ready', function() {
    $('.rsvp').on('click', function(e) {
        e.preventDefault()

        var user_id = $(.rsvp).data('user-id')
        var rsvp_id = $(.rsvp_id).data('rsvp-id')

        $.ajax({
            type: 'POST',
            url: "users/" + user_id + "/rsvps/" + rsvp_id
        }).done(function(response){ console.log('hello?', response)
        })
    })
})

应用目前在ActionController::UnknownFormat in RsvpsController#update行与respond_to分解。此帖子是this one, which is trying to solve too many problems at once的扩展名。

日志

Processing by RsvpsController#update as HTML
  Parameters: {"utf8"=>"✓", "rsvp"=>{"event_id"=>"16", "status"=>"attending"}, "user_id"=>"1", "id"=>"11"}
  Rsvp Load (3.3ms)  SELECT  "rsvps".* FROM "rsvps" WHERE "rsvps"."id" = $1 LIMIT $2  [["id", 11], ["LIMIT", 1]]
   (0.2ms)  BEGIN
  Event Load (2.5ms)  SELECT  "events".* FROM "events" WHERE "events"."id" = $1 LIMIT $2  [["id", 16], ["LIMIT", 1]]
  User Load (1.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  SQL (0.7ms)  UPDATE "rsvps" SET "status" = $1 WHERE "rsvps"."id" = $2  [["status", 2], ["id", 11]]
   (2.4ms)  COMMIT
Completed 406 Not Acceptable in 82ms (ActiveRecord: 20.6ms)



ActionController::UnknownFormat (ActionController::UnknownFormat):

app/controllers/rsvps_controller.rb:19:in `update'

更新

在我的路线文件中,我做了resources :rsvps, defaults: { format: 'js' }。这使应用程序以JS而不是HTML处理请求,但现在它呈现update.js.erb文件。 DB会更新,但不会根据需要进行部分重新加载。

1 个答案:

答案 0 :(得分:1)

试试这个

$.ajax({
        type: 'POST',
        url: "users/" + user_id + "/rsvps/" + rsvp_id,
        contentType: "text/javascript"

    }).done(function(response){ 
       console.log('hello?', response)
    })

或者

 $.ajax({
        type: 'POST',
        url: "users/" + user_id + "/rsvps/" + rsvp_id.js
    }).done(function(response){ 
       console.log('hello?', response)
    })