如何使用Node.js和Express在JavaScript中使用GET请求更改页面?

在这个应用程序,用户有一个表,他们可以input数据。 每行有一个“编辑”button,当他们点击那个button时,我想把他们带到一个叫“/ update”的新页面,在那里他们可以修改那个行的值。

我现在已经这样做了,当他们点击更新button时,它会运行editRow函数,传递表的id和行中的数据。 但是,我无法弄清楚如何让路线正常工作。

我使用的是Node.js,Express,Handlebars,但没有使用 jQuery。

app.js (服务器端)

 app.get('/update', function(req,res){ var context = {}; context.tableID = req.ID; context.element = req.element; res.render('update', context); }); 

update.handlebars

 <h1>test for now</h1> 

main.handlebars

 <!doctype html> <html> <head> <title>Workout Tracker</title> <link rel="stylesheet" href="css/style.css"> <script src="scripts/buttons.js" type="text/javascript"></script> </head> <body> {{{body}}} </body> </html> 

buttons.js (客户端)

 function editRow(tableID, element) { var httpRequest; httpRequest = new XMLHttpRequest(); if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'); } httpRequest.open('GET', 'http://localhost:3000/update'); httpRequest.send(); }; 

使用上面的新configuration,我现在可以到达/update代码,但render似乎并没有发生。 服务器或客户端控制台中没有错误消息。

正如你的错误所说, XMLHttpRequest对象上没有get函数。 我想你的意思是使用req.open来代替。

你可以参考这个文档,它将告诉你如何使用XMLHttpRequest进行reuqests: https : //developer.mozilla.org/enUS/docs/AJAX/Getting_Started#Step_3__A_Simple_Example