簡體   English   中英

如何從前端JavaScript發送JSON數據到使用Python搭建的后端Server Flask

[英]How to send JSON data from front-end JavaScript to the Back-end Server built by using Python Flask

我正在使用一個簡單的 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>

您可以使用 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)
      });

您可以將數據字符串化並將其發送到后端。

JSON.stringify(data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM