【问题标题】:Website not reading the correct local json网站未读取正确的本地 json
【发布时间】:2019-09-05 11:16:17
【问题描述】:

我创建了一个 HTML 站点,它使用 javascript/jQuery 读取 .json 并使用 PHP 写入它。 然后我有一个 c++ 后端,可以写入和读取相同的 .json。 我希望能够将玩家选择的按钮发送到 c++。

javascript 读取的 .json 并不总是我用 PHP 或 C++ 修改过的 .json。 它不会总是有更新的数据,获取更新数据的时间可以是瞬间的,几秒钟或几分钟。

我已尝试删除缓存并检查文件是否已更新

在我使用的网站上加载 .json:

var $JSONList = $('#JSONList');

  $.getJSON("json/playerMode.json", function(json) {
      console.log(json); // this will show the info it in firebug console
      var stringed = JSON.stringify(json);
      var response = JSON.parse(stringed);
      console.log(response); // this will show the info it in firebug console

      $.each(response, function(i, itt){

          $JSONList.append( "</br>" + itt.Name + " has pressed: " + itt.Button + " :(())");
      })

  });

这是由 &lt;button&gt; 调用的

由于这有时不会加载更新的 .json,有什么方法可以强制 javascript 再次加载本地 .json?

【问题讨论】:

  • 本地 JSON 在哪里?你能在你的问题中解释一下这种行为吗? :)
  • 强制提供新数据的快速解决方法是将?timetamp=[timestamp_here] 添加到被调用的url。或者,您可以使用 $.ajax 并在选项中设置 cache: false。
  • 本地 JSON 位于 main.php 的子文件夹中。我试试时间戳方法

标签: javascript jquery json


【解决方案1】:

首先,让我们假设这个 url 有效 - 除了缓存问题和地址以及其他问题。

  • 从快捷方式"json/playerMode.json" 更改为$ajax
  • 强制不缓存结果
  • 添加了fail以防万一
  • "&lt;br /&gt;" 的固定语法
  • 删除了不需要的代码,因为只要 JSON 有效,它就会被解析。如果它不是有效的 JSON 并且它只返回“一个看起来像 JSON 的字符串”,你应该使用 dataType: "text json" 来强制 jQuery 转换/解析 或考虑使用转换器(见下文)
  • PHP 可能需要header('Content-Type: application/json')
  • 如果您没有返回真正的 JSON 字符串,请使用转换器将其变为一个,请参阅使用转换器:https://api.jquery.com/jQuery.ajax/

来自https://api.jquery.com/jquery.ajax/

注意:将缓存设置为 false 仅适用于 HEAD 和 GET 请求。它通过将“_={timestamp}”附加到 GET 来工作 参数。

$.ajax({
  type: "GET",
  url: "json/playerMode.json",
  cache: false,
  data: "",
  dataType: "json" // force automatic parse of the JSON string returned
}).done(function(json) {
  console.log(json); // this will show the info it in firebug console
  // should not need
  // var stringed = JSON.stringify(json);
  // not needed, see above
  // var response = JSON.parse(json);
  //console.log(response); // this will show the info it in firebug console
  //$JSONList - what is this? it should be in here somewhere...so I did that
  let $JSONList = $('#JSONList');
  // should be parsed already, so changed to that
  $.each(json, function(i, itt) {
    $JSONList.append("<br />" + itt.Name + " has pressed: " + itt.Button + " :(())");
  }).fail(function(jqXHR, textStatus) {
    alert("Request failed: " + textStatus);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="JSONList"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    相关资源
    最近更新 更多