使用HTML提交按钮发送简单的HTTP请求

时间:2017-08-15 16:26:15

标签: javascript html http dom

我已将“提交”按钮添加到位于我服务器端的index.html页面

<form method="get" action="/start">
    <h5>Start Ad-Placer!</h5>
    <input type="submit" value="Start">
</form>

我需要按钮只需向http发送http://127.0.0.1:8484/get/start请求即可启动某个流程。然后,一旦过程完成几秒钟后,我只需显示一条带响应消息的警告消息,确认已完成。

如何以最少的努力(不使用JQuery或其他库)来实现这一目标。

1 个答案:

答案 0 :(得分:2)

如果您尝试这样的操作,您可以发送HTTP请求,然后提醒响应。只需将https://google.com更改为您的网址。

<h5>Start Ad-Placer!</h5>
<input type="submit" value="Start" onclick="submit()">

<script type="text/javascript">
    function submit() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                alert(xhr.response);
            }
        }
        xhr.open('get', 'https://google.com', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        xhr.send();
    }

</script>