需要实现html按钮访问REST获取资源

Need to implement html button to access REST get resource

本文关键字:REST 获取 资源 访问 按钮 实现 html      更新时间:2023-09-26

对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>