我正在使用 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; 
        } 
    }); 
} 

然后我收到一个错误: 未捕获类型错误:无法读取未定义的属性“长度” 在loadEvents处 我得到的不是一个 JSON 对象数组吗?我该如何解析它?

请您参考如下方法:

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


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!