写一段前后端交互的代码
时间: 2023-12-01 20:54:34 浏览: 19
Sure, here is an example code snippet for frontend and backend communication using AJAX:
Frontend (HTML/Javascript):
```html
<!DOCTYPE html>
<html>
<head>
<title>Example AJAX</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$('#submit_btn').click(function(){
var data = {
'name': $('#name_input').val(),
'age': $('#age_input').val()
};
$.ajax({
type: 'POST',
url: '/process',
data: JSON.stringify(data),
contentType: 'application/json;charset=UTF-8',
success: function(response){
alert(response.message);
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + errorThrown);
}
});
});
});
</script>
</head>
<body>
<label for="name_input">Name:</label>
<input type="text" id="name_input">
<br>
<label for="age_input">Age:</label>
<input type="number" id="age_input">
<br>
<button id="submit_btn">Submit</button>
</body>
</html>
```
Backend (Python/Flask):
```python
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello World!'
@app.route('/process', methods=['POST'])
def process():
data = request.get_json()
name = data['name']
age = data['age']
message = f'Hello {name}, you are {age} years old!'
response = jsonify({'message': message})
return response
if __name__ == '__main__':
app.run()
```
This example demonstrates a simple AJAX call to the '/process' endpoint with the name and age input from the user. The Flask backend receives the data, processes it and returns a JSON response with a simple message. Note that this is just an example and should be modified to fit your specific use case.