如何仅根据服务响应更新 javascript 中的单个元素

How to update individual element in javascript only depending on service response

我想更新一行内的值,我不想使用 OnReload,因为它会上传整个脚本,并且它取决于计时器,例如:每 5 秒重新加载一次...它不是我想要的是。除非有一些现代的东西可以用于此目的。 不确定,什么可以触发此更新以及如何制作此脚本? 例如:如果 item.updatelabel.value 与服务响应不同,则使用新值

更新 item.updatelabel
<script>
        fetch("http:myservice").then(res => res.json()).then(serviceResponse => {
            let newdoc = '';
            for (const item of serviceResponse) {
                newdoc += `
                    <div class="1">
                       <p id="name" class="title-text  ">${item.id}</p>
                      <h2 id="id" class="updatelabel-text">${item.updatelabel}</h2>(** This is the only thing to update)
                      <p class="small-text ">some fancy text</p>
                     </div>
                `
            }
            document.querySelector('.myclass').innerHTML = newdoc;
        })
    </script>

对于您的问题,我需要更多信息。

如果从服务响应中获取渲染数据,item.updatelabel.value 会有什么不同?

你写了"if item.updatelabel.value is different from the service response then update item"? .它看起来是一个项目数组,呈现的值是一个字符串。所以你想说“如果在 API 调用后更改了任何项目再次调用 API 或者你有硬编码项目并想从 API 调用更新它们?

当您说 "update that item" 时,您的意思是发出另一个 API 请求或更改应用程序页面的状态?

在特定时间间隔调用 ajax,然后在 ajax 的回调中替换文本

function fetchdata(){
 $.ajax({
  url: 'fetch.php',
  type: 'post',
  success: function(response){
   // Perform operation on the return value
    if($conditionsatisfy){
            document.querySelector('.myclass').innerHTML = newdoc;

  }
 });
}

$(document).ready(function(){
 setInterval(fetchdata,5000);
});

所以既然我对你的理解是正确的,你可能会遇到上述情况并继续打电话。 我认为您最好的解决方案是 Web Sockets。 https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API

使用 Websockets,您可以在客户端和服务器之间建立实时连接。查看 https://socket.io/ 可以轻松使用它。与新闻提要或 Instagram 一样,该页面将根据要求更新和运行。它将更新项目。实时,无需重新加载。

此外,根据您的 API 请求,您可以大大提高 ES7 的可读性

 const getData = async () => {
    //fetching data 
    let data = await fetch("https://jsonplaceholder.typicode.com/todos/1")
    //converting to json 
    let json = await data.json()
    console.log(json)

    let serviceResponse = json
     //do logic or return data here
 }

  getData()