Send simple HTTP request with HTML submit button

眉间皱痕 提交于 2021-02-07 18:40:18

问题


I have added a submit button to the index.html page that resides on my server side

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

I need the button to simply send a http request to http://127.0.0.1:8484/get/start to start some process. Then once the process is done after a few seconds, I need to simply display an alert message with the response message, acknowledging it is done.

How can I do that with minimum efforts (without using JQuery or other libraries).


回答1:


If you try something like this you can send a HTTP request and then alert a response. Just change https://google.com to your URL.

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


来源:https://stackoverflow.com/questions/45697176/send-simple-http-request-with-html-submit-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!