首页 > 解决方案 > 来自 fetch 的车把和 JSON 数据

问题描述

我有下面的代码并且有 2 个单独的问题,所以请多多包涵:

问题 1 [fetch ?]:当 JSON 更改时,显示的数据不会更改。听起来这是一个缓存问题,因为除了原始请求之外我看不到任何 HTTP 请求。如何强制每次重新下载 JSON 文件?

问题 2 [handlebars ?]: with $(document.body).append(html); 在循环中,它不断重写而不是编辑值。我怎样才能改变这个?

这是代码:

javascript.js:

async function fetch_json() {
    try {
        var resp = await fetch('http://localhost:8000/data.json', {mode: 'cors'});
        var jsonObj = await jsonify(resp);
        return jsonObj;
    } catch (error) {
        // all errors will be captured here for anything in the try block
        console.log('Request failed', error);
    }
}

html页面:

<script id="handlebars-demo" type="text/x-handlebars-template">
    <div>
        {{#each this}}
            Name : {{name}} Value : {{value}} <br>
        {{/each}}
    </div>
</script>
<script type="text/javascript">
    var test_data = [{ "name" : "john doe", "value" : "developer" },{ "name" : "bob boby", "value" : "developer2" }];
    setInterval(function() {
        test_data = fetch_json()
            .then(function(result) {
            html = templateScript(result);
            //$(document.body).append(html);
        })
    }, 1000);

    var template = document.getElementById('handlebars-demo').innerHTML;
    Compile the template data into a function
    var templateScript = Handlebars.compile(template);
    var html = templateScript(test_data);
    $(document.body).append(html);
</script>

任何帮助将不胜感激,谢谢!

标签: javascriptfetchhandlebars.js

解决方案


您应该创建一个 DOM 元素来保存您正在生成的 HTML。我<div id="content"></div>在示例中创建了。
您可以使用 $().html() 每次覆盖 HTML 而不是追加。
$('#content')选择 id=content 的 DOM 元素,然后.html(string)用字符串覆盖里面的 HTML。

缓存破坏的一种常见方法是将时间戳作为 url 查询参数附加到 url,我通过连接nocache='+new Date().getTime().
在生产中的正常使用中,通常在构建后为每个资源的每个版本生成一个唯一标识符。

// for demo purposes, overwrite value property with username property
jsonify = x => x.json().then(x => x.map(x => ({ ...x,
  value: x.username
})));

async function fetch_json() {
  try {
    // append timestamp to prevent caching
    var resp = await fetch('https://jsonplaceholder.typicode.com/users?nocache=' + new Date().getTime(), {
      mode: 'cors'
    });
    var jsonObj = await jsonify(resp);
    return jsonObj;
  } catch (error) {
    // all errors will be captured here for anything in the try block
    console.log('Request failed', error);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.6/handlebars.js" integrity="sha256-ZafrO8ZXERYO794Tx1hPaAcdcXNZUNmXufXOSe0Hxj8=" crossorigin="anonymous"></script>

<div id="content"></div>

<script id="handlebars-demo" type="text/x-handlebars-template">
  <div>
    {{#each this}} Name : {{name}} Value : {{value}} <br> {{/each}}
  </div>
</script>
<script type="text/javascript">
  var test_data = [{
    "name": "john doe",
    "value": "developer"
  }, {
    "name": "bob boby",
    "value": "developer2"
  }];
  setInterval(function() {
    test_data = fetch_json()
      .then(function(result) {
        html = templateScript(result);
        $('#content').html(html);
      })
  }, 2000);

  var template = document.getElementById('handlebars-demo').innerHTML;
  //Compile the template data into a function
  var templateScript = Handlebars.compile(template);
  var html = templateScript(test_data);
  $('#content').html(html);
</script>


推荐阅读