【问题标题】:How to send JSON data from front-end JavaScript to the Back-end Server built by using Python Flask如何将 JSON 数据从前端 JavaScript 发送到使用 Python Flask 构建的后端服务器
【发布时间】:2020-08-23 14:14:59
【问题描述】:

我正在使用一个简单的 HTML 表单从用户那里获取一些简单的数据。我希望首先在前端使用 JavaScript 过滤该数据,如果一切正常,我将使用前端本身的 JavaScript 将收集到的数据转换为 JSON 格式。

现在我想要在 JavaScript 中发送 JSON 格式的数据以发送到后端。

function fun(){
    let user = document.getElementById('user').value
    let password = document.getElementById('password').value

    let data = {
        "user": user,
        "password": password
    }
    console.log(data); // this data needs to be sent to the backend
    return true
}
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="main.css">
    <title>Data Entry</title>
</head>
<body>
    <div>
        <form action="" onsubmit="return fun()">
            <label for="user">user</label>
            <input type="text" name="user" id="user">
            <label for="password">password</label>
            <input type="password" name="password" id="password">
            <input type="submit" value="submit">
        </form>
    </div>
    <script src="code.js"></script>
</body>
</html>

【问题讨论】:

    标签: javascript python json flask


    【解决方案1】:

    您可以使用 fetch API。

    例如,您可以在 fun() 中使用以下代码:

     fetch('your-python-server', {
            method: 'post',
            body: JSON.stringify(data)
          }).then(function(response) {
            return response.json();
          }).then(function(data) {
            console.log("Data returned from python server", data)
          });
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2021-06-12
      • 2018-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多