我正在学习这两个教程,
并在 Rails 中实现一个简单的评论系统。但是,我在处理提交时遇到了问题。我实现了一个简单的 AJAX POST 请求来发送我的表单数据(作为状态)。它看起来像这样:
var CommentForm = React.createClass({
handleChange: function(e) {
var name, obj;
name = e.target.name;
return this.setState((
obj = {},
obj["" + name] = e.target.value,
obj
));
},
handleSubmit: function(e) {
e.preventDefault();
var author = React.findDOMNode(this.refs.author).value.trim();
var text = React.findDOMNode(this.refs.text).value.trim();
if(!text || !author) {
return;
}
$.post(this.props.postUrl, {comment: this.state}, null, "application/json");
React.findDOMNode(this.refs.author).value = '';
React.findDOMNode(this.refs.text).value = '';
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="text" placeholder="Your name" ref="author" name="author" onChange={this.handleChange} />
<input type="text" placeholder="Say something..." ref="text" name="text" onChange={this.handleChange} />
<input type="submit" value="Post" />
</form>
);
}
});
当我检查控制台时,看起来它正在传递到正确的路由和正确的参数,除了没有authenticity_token参数。这是控制台中内容的屏幕截图。
在我提供的第一个链接中,据说 jquery_ujs 处理生成真实性 token 并将其传递给 Ajax POST。然而,就我而言,情况并非如此。我错过了什么?
编辑: 我有一些答案可以解决我的问题。但是,我仍然好奇我的代码和本教程中的代码有何不同?
最佳答案
这是因为您的 render
方法中缺少传递 authenticity_token
。您可以禁用真实性检查(不推荐),或者使用真实性 token 交付呈现的表单。
在这种情况下,我建议使用 Gon 将 Controller 变量干净地传递给 JS: https://github.com/gazay/gon
安装时:
在您的 Controller 方法中:
gon.authenticity_token = form_authenticity_token
在你的 react 类中:
<form className="commentForm" onSubmit={this.handleSubmit}>
<input type="hidden" name="authenticity_token" value={gon.authenticity_token} />
<input type="text" placeholder="Your name" ref="author" name="author" onChange={this.handleChange} />
<input type="text" placeholder="Say something..." ref="text" name="text" onChange={this.handleChange} />
<input type="submit" value="Post" />
</form>
关于ruby-on-rails - Rails 不生成真实性 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32538808/