简体   繁体   English

HTML按钮发送发送请求以从表中的.json检索信息

[英]Html button to send a post request to retrieve information from .json in a table

I have a simple html file that has a button called Display Animal. 我有一个简单的html文件,其中包含一个名为Display Animal的按钮。 I have a seperate .json file that has various animals stored in some way. 我有一个单独的.json文件,其中以某种方式存储了各种动物。 What I am trying to do is on click of Display Animal I want to fetch the information from this json file and display it in a table on the screen. 我想做的是单击显示动物,我想从此json文件中获取信息,并将其显示在屏幕上的表格中。 I am using Express, Node, jQuery and Javascript. 我正在使用Express,Node,jQuery和Javascript。 Note that I am running server that displays the simple html file. 请注意,我正在运行显示简单html文件的服务器。 I am little unsure of the structure of how to do this? 我不太确定如何执行此操作的结构? Like in my html file do I have my onClick method there or in my server file? 就像在html文件中一样,我是否在其中或在服务器文件中拥有onClick方法? Also, how do I fetch this information? 另外,我该如何获取此信息? I am trying to accomplish this using GET or POST requests. 我正在尝试使用GET或POST请求来完成此任务。

Are you using a front-end library (like jQuery or Angular) or are you trying to do this natively with JavaScript? 您是在使用前端库(如jQuery或Angular),还是试图通过JavaScript本地执行此操作?

If the former, there are HTTP request APIs built into each (eg jQuery.POST() , or $http ). 如果是前者,则每个HTTP内建有HTTP请求API(例如jQuery.POST()$http )。 If the latter, you'll want to look into native XMLHttpRequest . 如果是后者,则需要查看本机XMLHttpRequest

Not a sophisticated answer, but your question is very broad. 这不是一个复杂的答案,但是您的问题非常广泛。 I'll leave reading the documentation to you. 我将留给您阅读文档。

Create a get service on your backend, with express it would be something like 在您的后端上创建一个get服务,使用express就像

var app = express();

app.get ('/animals', function (req, res){ 
// your code to parse and return your list of animals, function (err, data) {
res.end (data) }

That's not 100% working code but gives you an idea how the get will be formatted. 那不是100%可用的代码,但可以让您了解如何格式化get。

Then you can either use jquery.get () with your button onclick or write out a javascript xmlhttprequest. 然后,您可以在按钮onclick上使用jquery.get()或写出javascript xmlhttprequest。

Jquery would be easier but for you want to do it yourself there are tons of tutorials on writing a xhr in javascript. jQuery会更容易,但是对于您自己想做的话,有很多关于用JavaScript编写xhr的教程。

EDIT: I wrote this in response to a get request. 编辑:我写这是为了响应get请求。 If you want to use post it's essentially the same, use jquery.post () as the other answer suggests and instead of app.get it would be app.post. 如果要使用post,它实际上是相同的,请按照其他答案的建议使用jquery.post(),而不是app.get,它将是app.post。

For data like animals I'd use get, you are only showing information with no need to change it and a unless you are passing sensitive information get will serve your purposes fine. 对于像我将使用的动物这样的数据,get只是显示信息而无需更改它,除非您传递敏感信息,否则get会很好地满足您的目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM