无法从HTTP GET获取数据-Javascript

时间:2018-06-23 19:11:50

标签: javascript java json http spring-boot

我正在使用SpringBoot。在“ / api / events”中,我有一个事件列表。这是返回该列表的Java代码:

@GetMapping(path = "/api/events", produces = "application/json")
@Transactional
public @ResponseBody List<?> getEvents() {
    Query q = entityManager
            .createQuery("SELECT DISTINCT e FROM Event e JOIN e.blocks b WHERE b.begin > :currDate")
            .setParameter("currDate", new Date());
    return q.getResultList();
}

/ api / events中的数据如下所示:

[
  {"eventId":1,"title":"Test Event","owner":{"nick":"asd","mail":"abc@qq.pl","userId":5},"blocks":[{"blockId":1,"begin":"2018-01-01T11:00:00.000+0000","end":"2018-01-01T14:00:00.000+0000","minPerSlot":10},{"blockId":2,"begin":"2018-08-01T10:00:00.000+0000","end":"2018-08-01T13:00:00.000+0000","minPerSlot":10}]},
  {"eventId":3,"title":"Test2","owner":{"nick":"asd","mail":"abc@qq.pl","userId":5},"blocks":[{"blockId":3,"begin":"2018-08-01T10:00:00.000+0000","end":"2018-08-01T13:00:00.000+0000","minPerSlot":10}]}
]

在JS中,我想加载该数据。我正在使用以下代码:

function loadEvents() {
  var events = httpGet("/api/events");
  var len = events.length;
}

var getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
        callback(null, xhr.response);
    } else {
        callback(status, xhr.response);
    }
  };
  xhr.send();
};

function httpGet(theUrl) {
  getJSON(theUrl,
    function(err, data) {
        if (err !== null) {
            alert('Something went wrong: ' + err);
        } else {
            return data;
        }
    });
}

然后我收到一个错误: Uncaught TypeError: Cannot read property 'length' of undefined at loadEvents 我得到的是不是JSON对象数组?我应该如何解析?

1 个答案:

答案 0 :(得分:1)

httpGet实际上并没有向调用者返回任何内容。 如果要使用回调模式,则需要执行以下操作:

function loadEvents() {
  var events = getJSON("/api/events", function(err, events) {
    if (err) throw Error(err); // error handle here
    // logic here
    var len = events.length;
  });
}

var getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
        callback(null, xhr.response);
    } else {
        callback(status, xhr.response);
    }
  };
  xhr.send();
};