每次用户在输入字段中输入数字时调用 http get

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

提问人:Lewin Muzvonda 提问时间:2/19/2023 最后编辑:Lewin Muzvonda 更新时间:2/20/2023 访问量:113

问:

你如何让 JavaScript 每次在输入时输入数字时都发送 http get。(输入更改不起作用)

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

**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("change", function() {

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

        });
JavaScript jQuery 事件 获取 AddEventListener

评论


答:

1赞 lemek 2/19/2023 #1

好吧,事件可能不是你想象的那样。基本上,它会在“模糊”上触发,也就是从您的输入中改变焦点。你要挂钩的是事件。在这里你可以读到关于“变化”事件的深度解释 链接changeinput

  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 请求是一个好主意。我建议对它使用一些效果。debounce

评论

0赞 Lewin Muzvonda 2/20/2023
谢谢lemek。正是我需要的。将检查去抖动。
1赞 blek__ 2/19/2023 #2

要无延迟地监听事件,请使用
(前提是您有 jquery)
$(...).on('input change', () => {...})

也许也可以,但我没有检查它。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());
            // do what you want with reponse from now on
            // console.log(response)
        }
    ).catch((err) => console.error);
});

顺便说一句,在用户编辑输入时执行大量请求将对服务器性能不利,并可能触发速率限制。在我看来,如果你在触发 API 调用的输入附近放置一个重新加载按钮(从性能和 UX 的角度来看),那将是最佳实践