【问题标题】:Cannot get data from HTTP GET - Javascript无法从 HTTP GET 获取数据 - Javascript
【发布时间】:2018-12-02 21:33:45
【问题描述】:

我正在使用 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 对象数组吗?我该如何解析呢?

【问题讨论】:

    标签: javascript java json http spring-boot


    【解决方案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();
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多