【问题标题】:Response generates TypeError just on Firefox and Safari响应仅在 Firefox 和 Safari 上生成 TypeError
【发布时间】:2018-04-18 17:24:17
【问题描述】:

我正在使用 Ajax 获取响应并根据设备 ID 缓存一些选择器,然后在页面执行期间进行操作,如下所示:

$updateRate = 300000;
$devices_temperature_integer = []
$devices_temperature_decimal = []
$devices_humidity = []
$devices_luminosity = []
$devices_atm_pressure = []

$(".monitoring.weather_monitoring").ready(function() {
  cacheInfo();
  getInfo();

  $allTimer = setInterval(
    function() {
      getInfo();
    },
    $updateRate
  );
  return false;
});

function cacheInfo() {
  $.ajax({
    type: "GET",
    url: "/get_all_current_weather_infos",
    dataType: "json",
    success: function(response){
      for (i = 0; i < response.length; i++) {
        $devices_temperature_integer[i] = $('#device-'+response[i][0].id+"-temperature-integer");
        $devices_temperature_decimal[i] = $('#device-'+response[i][0].id+"-temperature-decimal");
        $devices_humidity[i] = $('#device-'+response[i][0].id+"-humidity");
        $devices_luminosity[i] = $('#device-'+response[i][0].id+"-luminosity-data");
        $devices_atm_pressure[i] = $('#device-'+response[i][0].id+"-atm_pressure");
      }
    }
  });
  return false;
}

function getInfo() {
  $.ajax({
    type: "GET",
    url: "/get_all_current_weather_infos",
    dataType: "json",
    success: function(response){
      for (i = 0; i < response.length; i++) {
        $temp = response[i][1].data.toFixed(1);
        $intPart = ($temp+"").split(".")[0];
        $decPart = ($temp+"").split(".")[1];
        $devices_temperature_integer[i].html($intPart)  //Error here
      }
    }
  });
  return false;
}

它在 Chrome 上运行顺利,但我在 Safari 和 Firefox 上得到TypeError: $devices_temperature_integer[i] is undefined(这是我正在操作的第一个数组)。此外,有时如果我在这些浏览器上不断刷新页面,错误就会消失并且页面可以正常工作。知道发生了什么吗?

【问题讨论】:

  • 我没有看到你从回复中得到$devices_temperature_integer。那么它是从哪里来的呢?
  • @CRice,我固定在那里。
  • 不过,我没有在您的代码中看到您初始化 $devices_temperature_integer 的任何地方。您是否在 sn-p 中遗漏了一条看起来像 $devices_temperature_integer = [] 的行?
  • 可能getInfo中的ajax请求完成之前来自cacheInfo的请求,所以当getInfo成功函数运行时,$devices_temperature_integer仍然为空。如果您在getInfo 成功回调中console.log($devices_temperature_integer.length),它会显示什么?
  • @CRice 你是对的。一个 Ajax 调用有时会在另一个之前完成。我使用了$.ajax({ ... }).done(getInfo),它已修复。

标签: javascript jquery ruby-on-rails ajax


【解决方案1】:

一个 Ajax 调用在另一个会提供一些参数的调用之前完成。所以我使用$.ajax({ ... }).done(getInfo) 来防止这种情况发生。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-12
    • 2020-03-25
    • 2016-07-25
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    相关资源
    最近更新 更多