【问题标题】:Loading JSON data via Javascript [duplicate]通过Javascript加载JSON数据[重复]
【发布时间】:2020-04-29 12:19:51
【问题描述】:

我正在使用“Ion.RangeSlider”库。我正在尝试通过 JSON 加载值,但无法让滑块接受“来自”字段。我不能硬编码值,因为用户可以更改它。

$(function(){
  'use strict'
  $('#rt').ionRangeSlider({
    min: 100,
    max: 100000,
    step: 10,
    from: loaddata(), -> Doesn't get the data from the function even though it prints it to the console.
    postfix: "ms",
    prefix: "Response Time: "
  });
});

function loaddata(){
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var myObj = JSON.parse(this.responseText);
      //document.getElementById("rt").value = myObj.response_time; -> Changing the value of the slider doesn't work as well
      console.log(myObj.response_time); -> Prints 2000 to the console
      return myObj.response_time;
    }
  };
  xmlhttp.open("GET", "api/settings.json", true);
  xmlhttp.send();
}

我的 json 文件:

{"response_time":7120,"led":0,"device_ip":"192.168.1.1"}

【问题讨论】:

    标签: javascript json rangeslider


    【解决方案1】:

    loaddata() 不返回任何内容,这就是原因。 AJAX 请求是异步的。从服务器返回的数据会在稍后的某个时间到达onreadystatechange 回调函数,只要服务器处理了请求并提供了响应。数据不会,也不能从 loaddata() 返回 - 尤其是因为 loaddata 函数在执行回调时已经完成

    您试图从onreadystatechange 回调中返回数据,但回调函数是由XmlHttpRequest 对象中的代码执行的,因此返回的值会回到那里 - 但该对象对它不感兴趣,您的代码无法访问它。

    您需要先获取数据,然后从 onreadystagechange 回调中运行一个函数来初始化 rangeslider,并传入下载的数据。

    例如像这样:

    $(function(){
      'use strict'
      loaddata();
    });
    
    function loaddata(){
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          var myObj = JSON.parse(this.responseText);
          console.log(myObj.response_time); -> Prints 2000 to the console
          loadRangeSlider(myObj.response_time);
        }
      };
      xmlhttp.open("GET", "api/settings.json", true);
      xmlhttp.send();
    }
    
    function loadRangeSlider(from)
    {
      $('#rt').ionRangeSlider({
        min: 100,
        max: 100000,
        step: 10,
        from: from
        postfix: "ms",
        prefix: "Response Time: "
      });
    }
    

    另见How do I return the response from an asynchronous call?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2021-02-08
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多