JavaScript: AJAX call w/ Flask
2021. 8. 14. 22:26ㆍFrontend/Web programming
- 목차
반응형
JavaScript side
First thing, you need to do to make an AJAX call from JavaScript is just adding ajax call code using jQuery as follow.
<!--index.html-->
<html>
<head>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<p id="example">AJAX</p>
<input type="text" id="id1" placeholder="id">
<input type="text" id="password1" placeholder="password">
<input type="text" id="email1" placeholder="email">
<input type="button" id="execute" value="execute">
<script>
$('#execute').click(function(){
var id = $('#id1').val();
var password = $('#password1').val();
var email = $('#email1').val();
var postdata = {
'id':id, 'password':password, 'email':email
}
$.ajax({
type: 'POST',
url: '{{url_for("ajax")}}',
data: JSON.stringify(postdata),
dataType : 'JSON',
contentType: "application/json",
success: function(data){
alert('success: ' + data.result2['id']+" " +
data.result2['password']+ " " + data.result2['email'])
},
error: function(request, status, error){
alert('ajax failure')
alert(error);
}
})
})
</script>
</body>
</html>
server side
At Flask server, what we need to implement to receive the POST request from client side is adding a new route function.
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/ajax', methods=['POST'])
def ajax():
data = request.get_json()
print(data)
return jsonify(result = "success", result2 = data)
That's all what we need to do for Ajax call from both sides.
반응형
'Frontend > Web programming' 카테고리의 다른 글
TypeScript (0) | 2021.12.05 |
---|---|
Update values of the Flask forms in JavaScript section (0) | 2021.09.02 |
Flask: update form value at JavaScript code (0) | 2021.08.14 |
JavaScript, HMLT: changing color of selected row in table (0) | 2021.08.14 |
JavaScript "Failed to find a valid digest in the 'integrity' attribute ..." (0) | 2021.08.13 |