gpt4 book ai didi

javascript - 无法从 HTTP GET 获取数据 - Javascript

转载 作者:行者123 更新时间:2023-12-02 11:05:33 25 4
gpt4 key购买 nike

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

关于javascript - 无法从 HTTP GET 获取数据 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51004317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com