2017-02-26 40 views
2

所以我請求並從服務器獲取的對象是這樣的:奇怪的行爲

$(document).ready(function() { 
     var req= $.getJSON("api/Appointments"); 
     req.done(function (data) { 
      $.each(data, function (key, value) { 
       $("#ul1").append("<li>" + value.Time + value.Company + "</li>"); 
      }); 
     }); 
     zahtev.fail(function (error) { 
      alert(error.statusText); 
     }) 
}); 

和它的作品,它顯示了<ul> 1項!
但是,當我嘗試這樣做:

$(document).ready(function() { 
     var req = $.getJSON("api/Appointments"); 
     req.done(function (data) { 
      if ((data.Time == "9:00") && (data.Company == "Laakkonen")) { 
       document.getElementById("A9").style.background = "red"; 
      } else { 
       alert("error1"); 
      } 

     }); 
     req.fail(function (error) { 
      alert(error.statusText); 
     }) 
    }); 

它給我的else聲明ERROR1!如果檢索到的JSON對象DID不是真的有9:00,那麼應該沒問題,但正如我前面在表格中提到的那樣,它有1個項目,其中有"9:00""Laakkonen" ...所以它應該爲紅色着色。

我在這裏錯過了什麼?

回答

1

如果你有數據的組合響應: -

$(document).ready(function() { 
    var req = $.getJSON("api/Appointments"); 
    req.done(function (data) { 
     var result = false; 
     $.each(data, function (key, value) { 
      if ((value.Time == "9:00") && (value.Company == "Laakkonen")) { 
       result = true; 
       return result; 
      } 
     }); 
     if (result == true) { 
      document.getElementById("A9").style.background = "red"; 
     } else { 
      alert("error1"); 
     } 
    }); 
    req.fail(function (error) { 
     alert(error.statusText); 
    }); 
}); 

如果你有一個數據作爲響應: -

if ((data[0].Time == "9:00") && (data[0].Company == "Laakkonen")) { 
    document.getElementById("A9").style.background = "red"; 
} else { 
    alert("error1"); 
} 
+0

是的,這工作,但爲什麼放在'VAR的結果=假'?它沒有它也行得通! – MicroDev

+0

所以當它找到「9:00」和「Laakkonen」的組合時,它會停止搜索?如果是這樣的話,那很可怕! – MicroDev

+0

恰好會發生在我的代碼中 –