Javascript 来自获取的句柄和JSON数据

Javascript 来自获取的句柄和JSON数据,javascript,fetch,handlebars.js,Javascript,Fetch,Handlebars.js,我有下面的代码,有两个单独的问题,因此请与我在这方面: 问题1[提取?]: JSON更改时,显示的数据不会更改。听起来像是缓存问题,因为除了原始HTTP请求之外,我看不到任何HTTP请求。如何强制每次再次下载JSON文件 第2期[车把?]:带有$document.body.appendhtml;在循环中,它不断地重新写入值,而不是编辑值。我怎样才能改变这个 代码如下: javascript.js: async function fetch_json() { try { v

我有下面的代码,有两个单独的问题,因此请与我在这方面:

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

第2期[车把?]:带有$document.body.appendhtml;在循环中,它不断地重新写入值,而不是编辑值。我怎样才能改变这个

代码如下:

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>

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

您应该创建一个DOM元素来保存正在生成的HTML。我已经在示例中创建了。 您可以使用$.html每次覆盖html,而不是追加。 $'content'选择id=content的DOM元素,然后用string覆盖.htmlstring中的HTML

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

//出于演示目的,请使用username属性覆盖value属性 jsonify=x=>x.json.thenx=>x.mapx=>{…x, 值:x.username }; 异步函数fetch_json{ 试一试{ //附加时间戳以防止缓存 var resp=等待获取'https://jsonplaceholder.typicode.com/users?nocache=“+new Date.getTime{ 模式:“cors” }; var jsonObj=等待jsonifyrep; 返回jsonObj; }捕捉错误{ //对于try块中的任何内容,都将在此处捕获所有错误 控制台。日志“请求失败”,错误; } } {{each this}}名称:{{Name}值:{{{Value}}{{/each}} var测试数据=[{ 姓名:约翰·多伊, 价值:开发者 }, { 姓名:bob boby, 值:developer2 }]; 设置间隔函数{ test_data=fetch_json .Then函数结果{ html=templateScriptresult; $'content'.htmlhtml; } }, 2000; var template=document.getElementById'handlebar-demo'.innerHTML; //将模板数据编译成函数 var templateScript=handlebar.compiletemplate; var html=templateScripttest_数据; $'content'.htmlhtml;
谢谢你,伙计。dom中更改的解决方案是有效的,而不是通过var resp=await fetch+new Date.getTime,{mode:'cors'}进行json获取;获取一个http错误::1---[27/May/2020 12:21:58]GET/data.json=1590546118289 http/1.1 404-这是文件not foundresp=wait fetch'localhost:8000/data.json?'+new Date.getTime,{mode:'cors'};工作,谢谢!!!您需要一个问号data.json?XXX将其指定为查询参数,否则它会将其视为文件名的一部分