英文:
Express.js - how to ask the server a yes/no question from client?
问题
我对客户端JavaScript感到舒适,但对服务器端代码是初学者。我的网站几乎都能正常运行,但遇到了问题。
在客户端中,我想让用户回答一个问题,点击“验证”按钮,然后客户端将询问Express服务器:“这是否是问题的正确答案?”并根据结果在输入旁边显示对号或X。
我似乎无法弄清楚正确的方法来实现这个目标。我在网上看到的POST示例都使用“res.send()”,会刷新整个页面。我看到了一些关于Promises和Ajax的内容,但对这些东西不太了解,也不确定是否是正确的学习方向。
有人可以指导我正确的方向吗?
英文:
I'm comfortable in client js, but I'm a server code beginner. Got my site almost all working, but hitting a wall.
In my client, I want the user to answer a question, push a "validate" button, and then the client will ask the Express server "is this the right answer to the question?" and display a checkmark or X next to the input based upon the result.
I can't seem to figure out the right method to do this. The POST examples I see online all use "res.send()" and would refresh the whole page. I come across stuff about promises and ajax, but don't know about those things, and not sure if it's the right road to go down learning.
Can anyone point me in the right direction?
答案1
得分: 0
你提到你对客户端JavaScript感到舒适。因此,你应该使用ajax来向服务器发出验证操作的后台调用。似乎当你进行POST时,你正在提交并因此刷新整个页面。然后,在你的Express应用程序中创建一个路由来处理ajax请求,这样就不需要刷新整个页面。
示例:
https://www.freecodecamp.org/news/how-to-use-fetch-api/
英文:
You mentioned you are comfortable in client js. So you should use ajax to make background calls to the server for the validate action you are trying to do. It seems like when you POST, you are submitting and therefore, refreshing the whole page. Then make a route in your express application to handle the ajax request and it won't need to refresh the whole page
Example:
https://www.freecodecamp.org/news/how-to-use-fetch-api/
答案2
得分: 0
你可以在互联网上查找axios或fetch。
这是一个关于如何使用AJAX从客户端发送数据到Node.js服务器而不刷新页面的教程:https://www.geeksforgeeks.org/how-to-send-data-from-client-side-to-node-js-server-using-ajax-without-page-reloading/
还有一个关于fetch的教程:https://www.freecodecamp.org/news/how-to-use-fetch-api/
要阻止页面在用户点击按钮时刷新,你需要阻止按钮的默认行为,你可以使用JavaScript来做到这一点。
给你的研究一个小提示:e.preventDefault()。
英文:
You can lookup for axios or fetch in the internet.
Here is a tutorial to do it : https://www.geeksforgeeks.org/how-to-send-data-from-client-side-to-node-js-server-using-ajax-without-page-reloading/
And another one about fetch : https://www.freecodecamp.org/news/how-to-use-fetch-api/
To stop the page from refreshing, when the user clicked in the button, you have to prevent the default behavior of the button, you can do this with javascript.
Just a little clue for your research : e.preventdefault()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论