如何在javascript中检索Python数组(Flask到React的通信)

0 人关注

我把Python数组转储到 json.dumps 的响应中,现在我正试图以Javascript列表的形式检索数据。

@app.route('/get_scales')
@cross_origin()
def get_scales():
    classes = inspect.getmembers(sys.modules['mingus.core.scales'], inspect.isclass)
    scales = [class_[0] for class_ in classes if ('Error' not in class_[0] and class_[0] != '_Scale')]
    return json.dumps(scales)
  getScales() {
    // create a new XMLHttpRequest
    var xhr = new XMLHttpRequest();
    // get a callback when the server responds
    xhr.addEventListener("load", () => {
      // update the state of the component with the result here
      console.log(xhr.responseText);
    // open the request with the verb and the url
    xhr.open("GET", "http://127.0.0.1:5000/get_scales");
    // send the request
    xhr.send();
    var formatted_response = JSON.stringify(xhr.responseText);
    console.log(JSON.parse(xhr.responseText));
    return xhr.responseText;

当我把getScales中的函数记录到xhr.responseText的控制台类型时,它显示的是String,但当试图用JSON.parse来解析它时,它抛出一个错误。试着先把它字符串化,像上面那样,也没有帮助。

python
arrays
reactjs
list
flask
tikej
tikej
发布于 2019-11-17
1 个回答
user12069894
发布于 2019-11-17
已采纳
0 人赞同

我不知道它给出了什么错误,但我认为这实际上是因为xhr.response,在你试图使用它时还没有出现。这是因为XMLrequest的功能是异步的,也就是说,当XMLrequest仍在等待响应时,你的其他代码仍在继续执行。试着这样做吧。

xhr.open('GET', url, false);

参数 "false "基本上表示你希望你的XMLrequest同步运行。所以你的其他代码将等待它完成。

请记住,在很多情况下,你的性能可能会因此而受到影响。 因此,如果你一次有多个XMLrequest,或者是Sequentially,你可以考虑使用HTML5Workers for this.

或者如果你不希望你的请求同步运作(如果你能避免让你的XMLrequest同步运作,你肯定应该这样做),你也可以尝试这样的东西(这样的东西对性能来说是最好的选择,所以如果你能使用它)。

  getScales() {
    // create a new XMLHttpRequest
    var xhr = new XMLHttpRequest();
    // get a callback when the server responds
    xhr.addEventListener("load", () => {
      // update the state of the component with the result here
      console.log(xhr.responseText);
      var formatted_response = JSON.stringify(xhr.responseText);
      console.log(JSON.parse(xhr.responseText));
      return xhr.responseText;
    // open the request with the verb and the url
    xhr.open("GET", "http://127.0.0.1:5000/get_scales");