因为某些原因,我需要用 js 创建一个 form,然后自行提交,但是遇到InvalidAuthenticityToken
。
不是 Ajax 提交。关键代码如下,页面里面有个 button,然后点击时执行testPost()
。
// from https://stackoverflow.com/questions/133925/javascript-post-request-like-a-form-submit
function post(path, params, method) {
method = method || "post"; // Set method to post by default if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
function testPost() {
post("/books", {foo: "bar"});
}
在 post 中加入authenticity_token
项,其值是 head 中的元数据 csrf-token 的值(由 Rails 生成)。
var token = $('meta[name="csrf-token"]').attr('content');