2

I am very new to jQuery and json. I am trying to get UK Bank Holiday data from the following API/link so that I can create a function which determines if a selected date is a working day.

https://www.gov.uk/bank-holidays.json

I had an error for No Transport which I fixed by putting in:

jQuery.support.cors = true;

I am now getting Access Denied. I have no idea how to gain access to this because as I say, I am still learning all this.

function IsWorkingDay(date) {
  var day = new moment(value, "DD-MM-YYYY").day();
  jQuery.support.cors = true;
  var bankHolidays = $.getJSON("https://www.gov.uk/bank-holidays.json").done(function(data) {
                                                                                   alert(data);
                                                                                 })
                                                                           .fail(function(a, b, c) {
                                                                                   alert(b + ',' + c);
  return day != 0 && day != 6;
}
                                                                          });

My question is in two phases:

  1. How do I get access? (Main question)
  2. How do I move on to access the data? I have downloaded the json onto my computer to look at, just how I am going to go about translating this to javascript is what I am struggling on.
4

2 回答 2

2

如果你被 CORS 阻塞了,并且服务不支持 JSONP,最简单的解决方法是为实际服务创建一个代理服务。因此,如果您在服务器上创建服务(与提供 javascript 的服务相同),您可以调用该服务,该服务反过来将从外部服务获取数据。在服务器端,无需担心 CORS。

我不知道你的后端是什么,但步骤如下:

  • 在您身边创建一个使用 URL 公开的服务(例如/myapp/workingday
  • 调用这个服务而不是真正的服务
  • 您的代理服务将获取 JSON 数据并将其返回给 javascript

编辑

我不知道 MVC4,但我怀疑它与 Spring MVC 的一些概念相同,所以这里有一个 Java 示例:

@Controller
public class HolidaysController {

    @RequestMapping("/workingday")
    public void isworkingDay(@RequestParam("day") Date day, HttpServletResponse response) {
        // Call external service and get JSON
        String json = callExternalService(day);
        response.setContentType("application/json");
        response.getWriter().write(json);
    }
}

在你的 javascript 中:

function IsWorkingDay(date) {
    var day = new moment(value, "DD-MM-YYYY").day();
    var bankHolidays = $.getJSON("/workingday").done(function(data) {
        // process data
    });
}
于 2013-04-17T11:51:33.160 回答
1

为此,您需要使用 jsonp,如此处所示

运行上面的代码会抛出一个无效的标签异常,正如这里解释的那样,正如@NilsH 所暗示的,这是由于服务器阻止了它

于 2013-04-17T11:44:26.673 回答