javascript 需要实现html按钮来访问REST获取资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24302263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need to implement html button to access REST get resource
提问by JustinBieber
Fairly new to REST and web application and would like to create a front-end site with a button and a place where a result is displayed.
对 REST 和 Web 应用程序相当陌生,并希望创建一个带有按钮和显示结果位置的前端站点。
I have REST API structured like this: http://hostserver.com/MEApp/MEService
我的 REST API 结构如下:http: //hostserver.com/MEApp/MEService
This returns a value when browsing to it.
这在浏览时返回一个值。
Now I would like to implement a GUI so that when you browse to c:\resourcebutton.html There will be a button and when I click on it, it will call the REST API resource and returns the result. If I understood REST correctly it should work like this.
现在我想实现一个 GUI,这样当你浏览到 c:\resourcebutton.html 时会有一个按钮,当我点击它时,它会调用 REST API 资源并返回结果。如果我正确理解 REST,它应该像这样工作。
I have a html code:
我有一个 html 代码:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
How and where should I insert the GET method to call the API? Is it common to use Javascript?
我应该如何以及在哪里插入 GET 方法来调用 API?使用 Javascript 很常见吗?
回答by maja
Yes, you have to do this with JavaScript. In fact, you need Ajax.
是的,你必须用 JavaScript 来做到这一点。实际上,您需要 Ajax。
To simplify things, you should download and include JQuery to your site, and then use something like this:
为了简化事情,您应该下载 JQuery 并将其包含到您的站点中,然后使用以下内容:
$.post( "http://hostserver.com/MEApp/MEService", function( data ) {
document.getElementById("demo").innerHTML = data;
//Or, in the JQuery-way:
$('#demo').html(data);
});
The jQuery Source can be found here: http://code.jquery.com/jquery-2.1.1.js
jQuery 源可以在这里找到:http: //code.jquery.com/jquery-2.1.1.js
Your html-file would then look like this:
您的 html 文件将如下所示:
<!DOCTYPE html>
<html>
<head>
<script src="the/Path/To/The/Downloaded/JQuery.js"></script>
<script>
//Usually, you put script-tags into the head
function myFunction() {
//This performs a POST-Request.
//Use "$.get();" in order to perform a GET-Request (you have to take a look in the rest-API-documentation, if you're unsure what you need)
//The Browser downloads the webpage from the given url, and returns the data.
$.post( "http://hostserver.com/MEApp/MEService", function( data ) {
//As soon as the browser finished downloading, this function is called.
$('#demo').html(data);
});
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
</html>