通过 ajax post 方法创建参数散列

Creating params hash via ajax post method

所以我想创建一个自定义参数散列,但我不确定该怎么做。我创建了一个 ruby 哈希(有点)。我没有其他想法

$("#bt-dw , #bt-up").click(function (event) {
  event.preventDefault();
  var id =  $(this).parent().attr("value");
  var up = $(this).attr("value");

  $.ajax({
    type: "POST",
    url: "/vote",
    data: "{:entry_id => '" + id + "',:up => '" + up + "'}",
    success: function () {
      console.log("post successful");
    },
    error: function () {
      console.log("post unsuccessful");
    }
  });
})

post 控制器

post '/vote' do
  @entry = Entry.get!(params[:entry_id]) rescue halt(404)
  @entry.vote(request.ip, params[:up] != 'false')
end

所以从你的评论看来你只是在创建一个单级 params 散列。

如果您想将数组或散列作为参数值发送,会稍微复杂一些。

有两种方法可以解决这个问题。

选项 1:在 ajax 请求

中将此值用于 data
data: { entry_id: id, up: up }

选项 2:在 url 而不是 data 中包含相同的信息:

url: `/vote?entry_id=${id}&up=${up}`

请注意,我在这里使用的是 ES6 模板字符串;这相当于:

url: ( "/vote?entry_id=" + id + "&up=" + up )