使用Jquery从API显示JSON数据 - 显示未定义

时间:2017-02-19 11:46:49

标签: javascript jquery html json api

我使用jquery和json数组来显示网站上的当前月相和日出/设定时间。这适用于日出/设置,但对于月相,我遇到了问题。

当"最近期"是在请求数据的同一天2其他字段被删除 - " currentphase"和" fracillum"。这意味着我不能每月4次显示相位或电流照明......

例如,下面的链接显示了fracillum和当前阶段: http://api.usno.navy.mil/rstt/oneday?date=today&coords=54.97N,1.61W&tz=0

但是从这些数据中省略: http://api.usno.navy.mil/rstt/oneday?date=01/28/2017&coords=54.97N,1.61W&tz=0

我已经编写了下面的代码来说明,如果curphase和fracillum未定义并且,那么最近的就是" New Moon"或者"满月"然后显示" 0%或" 100%"的fracillum分别

请有人确定我做错了什么吗?

$(document).ready(function(){
  $.get("http://api.usno.navy.mil/rstt/oneday?date=01/28/2017&coords=54.97N,1.61W&tz=0", function(data){
    checkPhase(data);
  });
});
$(document).ready(function(){
  $("#suntimes").click(function(){     
    $("#sun").toggle("slide");
  });
});
$(document).ready(function(){
  $("#moontimes").click(function(){     
    $("#moon").toggle("slide");
  });
});
$(document).ready(function(){
  $("#Mobilesuntimes").click(function(){     
    $("#Mobilesun").slideToggle();
  });
});
$(document).ready(function(){
  $("#Mobilemoontimes").click(function(){     
    $("#Mobilemoon").slideToggle();
  });
});

function checkPhase(data){
  if(data.curphase == "undefined" && data.closestphase.phase == "New Moon"){data.fracillum == "0%";}
  else if(data.curphase == "undefined" && data.closestphase.phase == "Full Moon")
  {data.fracillum == "100%";}

  $("#sun").append("<p><b>Newcastle, UK</b><br />Sunrise: " + data.sundata[1].time + " AM<br />Sunset: " + data.sundata[3].time + " PM</p>" );
  $("#moon").append("<p><b>Newcastle, UK</b><br />Percentage Illuminated: " + data.fracillum + "<br />Moon Phase: " + data.curphase + "</p>" );
  $("#Mobilesun").append("<p><b>Newcastle, UK</b><br />Sunrise: " + data.sundata[1].time + " AM<br />Sunset: " + data.sundata[3].time + " PM</p>" );
  $("#Mobilemoon").append("<p><b>Newcastle, UK</b><br />Percentage Illuminated: " + data.fracillum + "<br />Moon Phase: " + data.curphase + "</p>"
  );
}

2 个答案:

答案 0 :(得分:1)

使用typeof data.curphase == "undefined"代替data.curphase == "undefined"

&#13;
&#13;
var a = 1;

if ( typeof a == "undefined" )
  alert (" a is undefined" )

if ( typeof b == "undefined" ) 
  alert (" b is Undefined" )
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您想检查undefined值,请使用value === undefined代替value === "undefined",因为您要检查curphase是否为字符串"undefined"

此外,您不会为data.fracillum分配值,因为比较(data.fracillum == "0%";)而不是作业(data.fracillum = "0%";)。

你的情况应该是这样的:

if (data.curphase === undefined && data.closestphase.phase === "New Moon") {
  data.fracillum = "0%";
} else if (data.curphase === undefined && data.closestphase.phase === "Full Moon") {
  data.fracillum = "100%";
}