无法从HTTP get-Javascript获取数据
我用的是SpringBoot。在“/api/events”中,我有一个事件列表。下面是返回该列表的Java代码:无法从HTTP get-Javascript获取数据,javascript,java,json,http,spring-boot,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 DIS
@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();
}
在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:无法读取未定义的属性'length'
加载事件时
我得到的不是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();
};
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();
};