![](/img/trans.png)
[英]Form not submitting unless submitting twice. Ajax, vanilla js, django
[英]Submitting AJAX request using Vanilla JS
这是我当前的代码,我想在服务器端将一个对象(配方)推送到一个数组中,但是我还没走那么远。 现在,我只是试图在服务器上进行console.log(recipe)并变得不确定。
HTML:
<button type='button' class='btn btn-warning add-recipe'><i class="fa fa-book" aria-hidden="true" onclick='addRecipe(<%= JSON.stringify(recipe.author.id) %>)'></i></button>
JavaScript(客户端):
function addRecipe(recipe){
var xml = new XMLHttpRequest();
var recipe = recipe;
xml.open("POST", "/add-recipe", true);
xml.send({recipe: recipe});
}
JavaScript(服务器):
router.post('/add-recipe', function(req, res) {
var recipe = req.body.recipe;
console.log(recipe);
})
前端和后端都需要进行一些更改
function addRecipe(recipe){
var xml = new XMLHttpRequest();
var recipe = recipe;
xml.open("POST", "/add-recipe", true);
xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
xml.send(JSON.stringify({recipe: recipe}));
}
为了让后端在Express中使用json,您将必须使用主体解析器
var bodyParser = require('body-parser');
// I am assuming router the name of your express app
router.use(bodyParser.json());
router.post('/add-recipe', function(req, res) {
var recipe = req.body.recipe;
console.log(recipe);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.