如何从HTTP GET/POST获取变量值?JS传表单值至Python方法
Hey there! Let's walk through how to grab that key input value with JavaScript and send it to your Python backend. We'll use modern JavaScript (Fetch API) and a simple Flask server for the Python part—easy to set up and understand.
Step 1: Tweak Your HTML Form (Optional but Helpful)
First, let's add a couple id attributes to make selecting elements in JavaScript smoother, and prevent the default page reload on submit:
<head> <h1>Prueba TFG</h1> </head> <body> <form id="keywordForm" method="POST" action=""> Introduce KeyWord <input type="text" name="key" id="keyInput"> <input type="submit" name="submit" value="Submit"> </form> <script> // Our JavaScript logic goes here </script> </body>
Step 2: JavaScript to Grab Value & Send Request
Inside the <script> tag, we'll listen for the form's submit event, capture the input value, and send it to your Python server using the Fetch API:
const form = document.getElementById('keywordForm'); const keyInput = document.getElementById('keyInput'); form.addEventListener('submit', async (e) => { e.preventDefault(); // Stop the form from reloading the page const keyword = keyInput.value.trim(); if (!keyword) { alert('Please enter a keyword!'); return; } try { const response = await fetch('http://localhost:5000/receive-keyword', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ key: keyword }), // Package the value as JSON }); const result = await response.json(); console.log('Python server response:', result); alert('Keyword sent successfully!'); } catch (error) { console.error('Error sending keyword:', error); alert('Failed to send keyword.'); } });
This code:
- Catches the submit action without reloading the page
- Validates that a keyword was entered
- Sends the keyword to your Python server's
/receive-keywordendpoint as JSON - Handles success and error cases with feedback
Step 3: Python Backend to Receive the Value
We'll use Flask, a lightweight Python web framework, to create a server that listens for the POST request and processes the keyword.
First, Install Dependencies
Open your terminal and run:
pip install flask flask-cors
flask-cors fixes cross-origin request issues (since your frontend and backend will run on different ports by default).
Create the Python Server (app.py)
from flask import Flask, request, jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) # Allow cross-origin requests from your frontend @app.route('/receive-keyword', methods=['POST']) def receive_keyword(): # Parse the JSON data sent from JavaScript data = request.get_json() keyword = data.get('key') if not keyword: return jsonify({'error': 'No keyword provided'}), 400 # Here's where you can add your custom logic! print(f"Received keyword from frontend: {keyword}") # Example: Save to a database, run a search, process the text, etc. # Send a success response back to the frontend return jsonify({'success': True, 'received_keyword': keyword}) if __name__ == '__main__': app.run(debug=True)
This server:
- Sets up a
/receive-keywordendpoint that accepts POST requests - Extracts the keyword from the incoming JSON data
- Lets you add your own processing logic (like printing it, saving it, etc.)
- Sends a confirmation back to the JavaScript
Step 4: Test It Out
- Start your Python server: Run
python app.pyin your terminal (it will run onhttp://localhost:5000) - Open your HTML file in a web browser
- Enter a keyword and click "Submit"
- Check your terminal—you'll see the keyword printed there!
Alternative: Older Browser Support (XMLHttpRequest)
If you need to support browsers that don't have the Fetch API, use XMLHttpRequest instead:
form.addEventListener('submit', (e) => { e.preventDefault(); const keyword = keyInput.value.trim(); if (!keyword) { alert('Please enter a keyword!'); return; } const xhr = new XMLHttpRequest(); xhr.open('POST', 'http://localhost:5000/receive-keyword'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = function() { if (xhr.status === 200) { const result = JSON.parse(xhr.responseText); console.log('Python server response:', result); alert('Keyword sent successfully!'); } else { console.error('Error:', xhr.statusText); alert('Failed to send keyword.'); } }; xhr.onerror = function() { console.error('Network error occurred.'); alert('Network error.'); }; xhr.send(JSON.stringify({ key: keyword })); });
内容的提问来源于stack exchange,提问作者AntonioMJ

