【问题标题】:Sending JSON to AJAX from Python Flask [duplicate]从 Python Flask 将 JSON 发送到 AJAX [重复]
【发布时间】:2018-09-13 02:51:25
【问题描述】:

我正在尝试将数据从使用 Python 中的 Flask 制作的服务器发送到客户端并使用 AJAX 收集这些数据。我见过的很多例子都是用 jQuery 做的,但我想不用 jQuery。是否可以只使用没有 jQuery 的普通 Javascript 来做到这一点,我将如何构建这个功能?

【问题讨论】:

    标签: javascript python json ajax flask


    【解决方案1】:

    如果您不想使用 jQuery,可以在 javascript 中使用内置的 XMLHttpRequest 对象。其实用起来很简单,

    var url = 'www.yoursite.com/data.json';
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'json';
    xhr.open("GET", url, true);
    
    xhr.onload = function() {
        console.log("Status Code", this.status);
        console.log("Body", this.response);
    }
    xhr.send();
    

    【讨论】:

      【解决方案2】:

      您可以使用常规的 XmlhttpRequest:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

      更好的是,您可以使用 Fetch API:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

      来自 MDN 文档:

       fetch('http://example.com/movies.json')
        .then(function(response) {
          return response.json();
        })
        .then(function(myJson) {
          console.log(myJson);
        });
      

      Fetch 使用了 Promise,所以你应该使用它。

      【讨论】:

        猜你喜欢
        • 2016-09-13
        • 2019-09-25
        • 2019-02-08
        • 1970-01-01
        • 1970-01-01
        • 2020-08-09
        • 2023-03-30
        • 2018-05-20
        • 1970-01-01
        相关资源
        最近更新 更多