简体   繁体   English

如何使用Ajax向我的Rails控制器发出POST请求?

[英]How do I make a POST request to my Rails controller with Ajax?

I am trying to send information from my JavaScript game-state on the front end, to my controller and then database. 我试图将信息从前端的JavaScript游戏状态发送到控制器,然后发送到数据库。 I'm not getting any response, and I'm not sure why. 我没有任何回应,也不确定为什么。

Here's the listening event with the Ajax, containing the variable value ( score ) I want to send. 这是Ajax的监听事件,其中包含我要发送的变量值( score )。

$("#link-to-hq").click(function(){
 test = $.ajax({
          type: "POST",
          url:    "/users/:id",
          data: {dollars: score},
          datatype:"html",
          async: true
        });
});

And the button it listens to: 和它监听的按钮:

</script>

<%= link_to "Home", user_path(@user), id: 'link-to-hq' %> 

And the route I'm trying to hit: 而我想打的路线:

PATCH  /users/:id(.:format)                     users#update

Then, here's my controller: 然后,这是我的控制器:

def update
    @user = User.find(params[:id])
    new_dollars = params[:dollars]
    #store to database
    @user.dollars<<new_dollars
 end

I don't seem to be getting any feedback. 我似乎没有收到任何反馈。 Is my request or controller formulated incorrectly? 我的请求或控制器的公式是否正确?

EDIT 1 编辑1

I did indeed change the request, as per suggested: 我确实确实按照建议更改了请求:

$("#link-to-hq").click(function(){
  test = $.ajax({
          type: "PATCH",
          url:    "/users/<%= @user.id %>",
          data: {dollars: score},
          datatype:"html",
          async: true
        });
});

Its still unresponsive. 它仍然没有反应。

Heres my dev log info. 这是我的开发人员日志信息。 There are errors: 有错误:

Started PATCH "/users/0" for 127.0.0.1 at 2014-07-14 13:52:30 -0400
Processing by UsersController#update as */*
  Parameters: {"dollars"=>"1", "id"=>"0"}
  [1m[35mUser Load (0.6ms)[0m  SELECT  "users".* FROM "users"  WHERE                  "users"."remember_token" = '5b38b7021d2e00f6aecc21b29e2322d4f988c6eb' LIMIT 1
  [1m[36mUser Load (0.4ms)[0m  [1mSELECT  "users".* FROM "users"  WHERE "users"."id"    = $1 LIMIT 1[0m  [["id", 0]]
Completed 400 Bad Request in 5ms

ActionController::ParameterMissing (param is missing or the value is empty: user):
  app/controllers/users_controller.rb:85:in `user_params'
  app/controllers/users_controller.rb:66:in `update'

POST is for new requests. POST适用于new请求。

Try: 尝试:

type: "PATCH",

I believe this will also work: 我相信这也会起作用:

type: "PUT",

Also, make sure you specify :id as an actual number. 另外,请确保将:id指定为实际数字。

To expand on beautifulcoder's accurate answer, you need to both align the type with the route you're trying to hit, and make sure you're using real numbers in the ajax URL. 要扩展beautifulcoder的准确答案,您既需要将类型与要查找的路径对齐,还要确保在ajax URL中使用实数。 You've changed the URL to reference @user, but Javascript can't reference Ruby variables. 您已将URL更改为引用@user,但是Javascript无法引用Ruby变量。

The simplest way to tackle your current issue would be to pass the Ruby variable to a data attribute in your view: 解决当前问题的最简单方法是将Ruby变量传递给视图中的data属性:

# your view
<element id="some_id" data-user_id="<%= @user.id %>"></element>

# your javascript/jquery

$("#link-to-hq").click(function(){
  var id = $('#some_id').data('user_id');
  test = $.ajax({
      type: "PATCH",
      url:    "/users/" + id,
      data: {dollars: score},
      datatype:"html",
      async: true
    });
});

If the user is the current user, and you have, or could create, a current_user helper, you can also just make the action :id independent: 如果该用户是当前用户,并且您具有或可以创建current_user帮助器,则也可以使操作:id独立:

# javascript/jquery
$("#link-to-hq").click(function(){
  test = $.ajax({
      type: "PATCH",
      url:    "/users/update",
      data: {dollars: score},
      datatype:"html",
      async: true
    });
});

# routes.rb
PATCH  /users/update                   users#update

#users_controller.rb
def update
  @user = current_user
  new_dollars = params[:dollars]
  #store to database
  @user.dollars<<new_dollars
end

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

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