问题描述
问题:如果日期是银行假日,如何使用API返回布尔值?
我已经进行了一些研究,发现了一个很棒的免费的API,其中包含银行假期,但是我在使用它时遇到了麻烦: http ://holidayapi.com/
I have done some research and found a great, and free API which contains bank holidays, however I am having trouble using it: http://holidayapi.com/
如果我要使用此代码:
var year = 2016;
var month = 3;
var day = 25;
var isAHoliday = false;
$.getJSON(
"http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day, function (data) {
console.log(data); //DOES NOT DISPLAY IN CONSOLE
if (data.holidays.length > 0) {
// BANK HOLIDAY
isAHoliday = true;
}
else {
//IS NOT BANK HOLIDAY
//AND NOTHING NEEDS TO BE DONE
}
});
我希望能够返回true或false值,具体取决于它是否返回任何数据,但是由于未调用getJSON请求,我做错了什么,请有人纠正我哪里错了?
i want to be able to return a true or false value depending on if this returns any data or not, however im doing something wrong as the getJSON request is not being called, please could someone correct me where i have gone wrong?
http://holidayapi.com/v1/holidays?country = GB& year = 2016& month = 03& day = 25 返回{"status":200,"holidays":[{"name":"Good Friday","country":"GB","date":"2016-03-25"}]}
http://holidayapi.com/v1/holidays?country = GB& year = 2016& month = 03& day = 26 返回{"status":200,"holidays":[]}
看来这是引起问题的原因: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day;
如果我通过了上面2个URL之一,则我得到了正确的结果,我现在正在玩这个游戏
it appears this is causing an issue: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day;
if i pass one of the 2 URL's in above i get the correct result, I am having a play now with this
https://jsfiddle.net/dcxk6ens/
推荐答案
如果您只想在所选日期是假期时返回true
值,或者如果不是,则返回false
像这样:
If you simply want to return a true
value if the selected date is a holiday, or false
if it is not, you could use a function like this:
(请注意,由于不安全,jsfiddle将不会使用"http://"协议对URL执行任何AJAX调用.)
(Please note that jsfiddle will not execute any AJAX calls to URLs using the "http://" protocol, since it is not secure.)
function isDateAHoliday(y, m, d) {
var jsonURL = "http://holidayapi.com/v1/holidays?country=GB&year=" + y + "&month=" + m + "&day=" + d;
var isAHoliday = false;
$.getJSON(jsonURL, function (data) {
// If the date is a holiday
if (data.holidays.length > 0) {
// Do some things
isAHoliday = true;
}
// Check values
console.log("JSON DATA: ", data);
console.log("Holiday?: " + isAHoliday);
return isAHoliday;
});
}
isDateAHoliday("2016", "3", "25");
如果您还想返回假期的名称和国家/地区,则可以在if
语句内替换isAHoliday = data.holidays[0];
.
If you wanted to return the name and country of the holiday as well, you could substitute isAHoliday = data.holidays[0];
inside of the if
statement.
这篇关于使用HolidayAPI进行银行假期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!