如何根据文本字段更改发送POST请求? (不使用提交按钮)

时间:2019-09-21 01:45:16

标签: javascript html flask

我想拥有一个用户在文本字段中键入内容的应用程序。完成用户操作后,表单将自动“提交” POST请求。 (应该说,用户停止输入后要延迟2秒)。

我不知道该怎么做-我想象它需要一些JavaScript或更多的机器。我正在使用flask / Python。

我已经在SO中广泛搜索了这些解决方案,但找不到开始的地方。

1 个答案:

答案 0 :(得分:-1)

当用户更改输入字段的内容时执行JavaScript:

<input type="text" onchange="sendData()" id="myData">

https://www.w3schools.com/jsref/event_onchange.asp

,然后可以使用xmlhttprequest POST https://www.w3schools.com/js/js_ajax_http.asp

      var stuff = document.getElementById("myData").value;
      var xhr = new XMLHttpRequest();

      var p ='https://example.com/whereyouwantyourposttogo';
      xhr.open('POST', p, true);
      xhr.onreadystatechange = function() {
    //do your stuff when the POST data comes back
      };
//if you want to send JSON data do JSON.stringify(stuff) inside the send
//for example xhr.send(JSON.stringify(stuff));
      xhr.send(stuff);