Python BAKMR010399005
Python BAKMR010399005
### Flask
1. **Setup**:
```bash
```
```python
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
```
```python
@app.route('/data', methods=['POST'])
def data():
request_data = request.get_json()
response_data = {'message': 'Received', 'data': request_data}
return jsonify(response_data)
```
Ajax (Asynchronous JavaScript and XML) allows web pages to update asynchronously by exchanging data with a web
server behind the scenes. This means that parts of a web page can be updated without reloading the whole page.
```html
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="response"></div>
<script>
$(document).ready(function(){
$('#getDataButton').click(function(){
$.ajax({
url: '/data',
type: 'POST',
contentType: 'application/json',
},
error: function(error){
});
});
});
</script>
</body>
</html>
```
2. **Handling Responses**:
- When the button is clicked, an AJAX POST request is sent to the `/data` endpoint.
- The JavaScript code handles the response and updates the HTML content accordingly.
### Conclusion
Combining Flask with AJAX allows for creating dynamic and responsive web applications. Flask handles the backend logic
and routing, while AJAX ensures smooth and asynchronous data exchange, enhancing the user experience. This setup is
particularly effective for applications that require real-time updates or interactions without refreshing the page.