2

以下 JavaScript 向我的 rails 服务器发送一个XMLHttpRequest带有参数的参数recipe_num,我如何从控制器中提取数据?我试过params[:recipe_num]session[:recipe_num],两者都不起作用。

function getRules(recipe_num){
    var request = new XMLHttpRequest;
    request.open("POST", "/path/rules_json?format=json", true);
    var token = $("meta[name='csrf-token']").attr("content");
    request.setRequestHeader("X-CSRF-Token", token);
    request.onreadystatechange = function() {
        if(request.readyState == request.DONE){
            buildForm(JSON.parse(request.responseText));
        }
    };
    request.send("recipe_num=" + recipe_num);
};
4

1 回答 1

1

对于 Rails 5.1.2,

您可以通过 获取原始数据request.raw_post。如果您想将其用作params,则应添加Content-type标题。

# for string
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("prev_id="+pid+"&next_id="+nid);
# for json string
request.setRequestHeader("Content-type", "application/json");
request.send(JSON.stringify({ prev_id: pid }));

参考文件action_dispatch/http/parameters.rb

DEFAULT_PARSERS = {
    Mime[:json].symbol => -> (raw_post) {
      data = ActiveSupport::JSON.decode(raw_post)
      data.is_a?(Hash) ? data : { _json: data }
    }
  }
于 2017-07-19T02:00:28.887 回答