为了账号安全,请及时绑定邮箱和手机立即绑定

无法从HTTP GET获取数据-Javascript

无法从HTTP GET获取数据-Javascript

撒科打诨 2021-04-13 21:14:07
我正在使用SpringBoot。在“ / api / events”中,我有一个事件列表。这是返回该列表的Java代码:@GetMapping(path = "/api/events", produces = "application/json")@Transactionalpublic @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 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

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();

};


查看完整回答
反对 回复 2021-04-21
  • 1 回答
  • 0 关注
  • 237 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信