Javascript 如何在没有jquery的情况下使用ajax将数据发送到节点服务器?
我正在尝试学习如何使用ajax发送数据。单击submit按钮时,我希望Ajax将数据发送到特定的路由,该路由与数据和表单关联的路由无关。然而,Ajax似乎没有发送任何东西。我在脚本中添加了三条Javascript 如何在没有jquery的情况下使用ajax将数据发送到节点服务器?,javascript,html,node.js,ajax,Javascript,Html,Node.js,Ajax,我正在尝试学习如何使用ajax发送数据。单击submit按钮时,我希望Ajax将数据发送到特定的路由,该路由与数据和表单关联的路由无关。然而,Ajax似乎没有发送任何东西。我在脚本中添加了三条console.log()语句,但没有一条显示出来 HTML和AJAX代码 您需要将type=“button”添加到提交按钮,并使用preventDefault发出xmlhttp请求 const el=document.getElementById(“submitForm”); 如果(el){ el.
console.log()
语句,但没有一条显示出来
HTML和AJAX代码
您需要将
type=“button”
添加到提交按钮,并使用preventDefault
发出xmlhttp请求
const el=document.getElementById(“submitForm”);
如果(el){
el.addEventListener('click',addRecipe');
console.log(“步骤1”);
}
函数addRecipe(e){
e、 预防默认值();
变量配方={
参数1:'value1',
参数2:“值2”
};
console.log('步骤2')
让xml=newXMLHttpRequest();
open(“POST”,“/addrecipe”,true);
//指定要发送的数据类型
setRequestHeader(“内容类型”,“应用程序/json;字符集=utf-8”);
send(JSON.stringify(recipe));
console.log(“步骤3”);
}
提交
实际上,当点击提交
按钮时,将提交表单
,因此页面/数据将直接重定向到操作
页面
这就是为什么不执行addRecipe()
函数的原因,因为页面在执行之前被重定向
因此,如果要在提交表单之前执行addRecipe()
函数并通过Ajax发送数据
,则需要防止默认表单提交,执行代码,然后提交表单
:
function addRecipe(e) {
e.preventDefault();
var recipe = {
param1: 'value1',
param2: 'value2'
};
console.log('step 2')
let xml = new XMLHttpRequest();
xml.open("POST", "/add-recipe", true);
//Specify the type of data to be sent
xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
xml.send(JSON.stringify(recipe));
console.log('step 3');
//Get the form and submit it
form.submit();
}
我从来不知道一个元素可以连接多个类型。非常感谢。但是,能否向up update回答一个解释,为什么将type=“submit”附加到表单和偶数侦听器都不起作用?另外,您能否解释一下
e.preventDefault();
为什么需要它?
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
let urlencodedParser = bodyParser.urlencoded({extended: false});
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.listen(7000);
app.post('/add-recipe', function(req, res) {
var recipe = req.body.recipe;
console.log(recipe);
});
app.post('/submitData',urlencodedParser,function(req, res){
});
function addRecipe(e) {
e.preventDefault();
var recipe = {
param1: 'value1',
param2: 'value2'
};
console.log('step 2')
let xml = new XMLHttpRequest();
xml.open("POST", "/add-recipe", true);
//Specify the type of data to be sent
xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
xml.send(JSON.stringify(recipe));
console.log('step 3');
//Get the form and submit it
form.submit();
}