对 REST 和 Web 应用程序还很陌生,想创建一个带有按钮和显示结果的位置的前端站点。
我的 REST API 结构如下: http://hostserver.com/MEApp/MEService
浏览到它时返回一个值。
现在我想实现一个 GUI,这样当你浏览到 c:\resourcebutton.html 会有一个按钮,当我点击它时,它会调用 REST API 资源并返回结果。如果我正确理解 REST,它应该像这样工作。
我有一个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>
我应该如何以及在何处插入 GET 方法来调用 API?使用 Javascript 很普遍吗?
最佳答案
是的,您必须使用 JavaScript 来执行此操作。事实上,您需要 Ajax。
为了简化事情,您应该下载 JQuery 并将其包含到您的网站中,然后使用类似这样的东西:
$.post( "http://hostserver.com/MEApp/MEService", function( data ) {
document.getElementById("demo").innerHTML = data;
//Or, in the JQuery-way:
$('#demo').html(data);
});
jQuery 源代码可以在这里找到:http://code.jquery.com/jquery-2.1.1.js
您的 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>
关于javascript - 需要实现 html 按钮来访问 REST 获取资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24302263/