Call http get every time user enter a digit in an input field.

huangapple go评论60阅读模式
英文:

Call http get every time user enter a digit in an input field

问题

如何使 JavaScript 在输入框中每次输入数字时发送 HTTP GET 请求?(更改输入内容时不起作用)

当前代码仅在用户更改输入并离开字段时发送请求。

HTML

<input id="total" name="total" type="number" required>
<span id="converted"></span>

JS

var total = document.getElementById("total");
var converted = document.getElementById("converted");
total.addEventListener("input", function() {
    fetch("http://localhost:8000/api/convert/" + total.value)
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            converted.innerHTML = data.converted;
        });
});
英文:

How do you make JavaScript send http get every time you enter a digit on input. (On input change doesn't work)

Current Code only sends the request when user changes the input and leaves the field.

**HTML**

&lt;input id=&quot;total&quot; name=&quot;total&quot; type=&quot;number&quot; required&gt;
&lt;span id=&quot;converted&quot;&gt;&lt;/span&gt;

**JS**

      var total = document.getElementById(&quot;total&quot;);
      var converted = document.getElementById(&quot;converted&quot;);
      total.addEventListener(&quot;change&quot;, function() {

            fetch(&quot;http://localhost:8000/api/convert/&quot;+total.value)
            .then(function(response) {
                return response.json()
            })
            .then(function(data) {
                cconverted.innerHTML = data.converted; 
            });

        });

答案1

得分: 1

change 事件可能不是你想象的那样。基本上,它在“失焦”时触发,即在你的输入框失去焦点时触发。你想要监听的是 input 事件。你可以在这里阅读关于 change 事件的详细解释 链接

var total = document.getElementById("total");
total.addEventListener("input", function() {
    fetch("http://localhost:8000/api/convert/" + total.value)
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            cconverted.innerHTML = data.converted;
        });
});

然而,我认为对于每个用户输入都发送 HTTP 请求并不是一个好主意。我建议在这上面使用一些“防抖”效果。

英文:

Well, change event is probably not what you think it is. Basically it fires on "blur" aka changing focus from your input. What you want to hook into is input event. Here you can read about deep explanation of "change" event LINK

  var total = document.getElementById(&quot;total&quot;);
  total.addEventListener(&quot;input&quot;, function() {

        fetch(&quot;http://localhost:8000/api/convert/&quot;+total.value)
        .then(function(response) {
            return response.json()
        })
        .then(function(data) {
            cconverted.innerHTML = data.converted; 
        });

    });

However I don't think sending http request for every user input is a good idea. I would suggest using some debounce effect on it.

答案2

得分: 1

要实现无延迟监听事件,请使用 $(...).on('input change', () => {...})(假设你已经加载了 jQuery)。

也许 document.getElementById("...").addEventListener('input change', () => {...}) 也可以,但我没有检查过。

要实现你想要的功能,请使用列出的方法之一监听事件,并使用 fetch 执行请求。

$('#total').on('input change', () => {
    let el = $('#total');
    fetch('site.com/api?value=' + window.encodeURIComponent(el.text()))
        .then((response) => {
            if (!response.ok())
                throw new Error(response.status());
            // 从现在开始处理响应的内容
            // console.log(response)
        }
    ).catch((err) => console.error);
});

另外,当用户正在编辑输入时进行大量请求可能对服务器性能不利,并且可能触发速率限制。在我看来,最佳做法是在输入旁边放置一个重新加载按钮,触发 API 调用(从性能和用户体验的角度考虑)。

英文:

To listen to the event without a delay, use $(...).on(&#39;input change&#39;, () =&gt; {...})
(provided you have jquery)

Perhaps document.getElementById(&quot;...&quot;).addEventListener(&#39;input change&#39;, () =&gt; {...}) will work too, but i didn't check it.

To do what you want to do, listen to the event using one of the listed approaches and perform the request with fetch.

$(&#39;#total&#39;).on(&#39;input change&#39;, () =&gt; {
    let el = $(&#39;#total&#39;);
    fetch(&#39;site.com/api?value=&#39; + window.encodeURIComponent(el.text()))
        .then((response) =&gt; {
            if (!response.ok())
                throw new Error(response.status());
            // do what you want with reponse from now on
            // console.log(response)
        }
    ).catch((err) =&gt; console.error);
});

On a side note, performing a lot of requests when user is editing the input would be bad for server performance and could possibly trigger rate limits. In my opinion, it would be best practice if you'd put a reload button near the input which triggers the API call (from both performance and UX points of view)

huangapple
  • 本文由 发表于 2023年2月19日 20:21:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500102.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定