nrp*_*rph 4 forms node.js express
在我的第一个Node项目中,使用Express/Express资源库和Jade进行模板化.
根据docs生成默认映射.其中我们可以找到:
PUT /forums/:forum -> update
Run Code Online (Sandbox Code Playgroud)
然而,我没有看到提交价值的简单方法.
如何提交创建/更新?
可以轻松创建Jade表单和body解析器,但是如何提交此表单?请注意,express-resource定义了PUT方法(不是POST).
从快速指南:
当使用带有表单的PUT等方法时,我们可以使用名为_method的隐藏输入,该输入可用于更改HTTP方法.为此,我们首先需要使用methodOverride中间件,该中间件应放在bodyParser下面,以便它可以利用它包含表单值的req.body.
所以:
app.use(express.bodyParser());
app.use(express.methodOverride());
Run Code Online (Sandbox Code Playgroud)
并以您的形式:
<input type="hidden" name="_method" value="put">
Run Code Online (Sandbox Code Playgroud)
更新:据我了解提问者的新评论,nrph想要一种PUT使用ajax 提交方法的方法.这是一个使用jQuery的解决方案:
// Use this submit handler for all forms in document
$(document).on('submit', 'form', function(e) {
// Form being submitted
var form = e.currentTarget;
// Issue an ajax request
$.ajax({
url: form.action, // the forms 'action' attribute
type: 'PUT', // use 'PUT' (not supported in all browsers)
// Alt. the 'method' attribute (form.method)
data: $(form).serialize(), // Serialize the form's fields and values
success: function() {},
error: function() {}
});
// Prevent the browser from submitting the form
e.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3112 次 |
| 最近记录: |