📁static
└📄common.js
📁templates
└📄index.html
📄app.py
이제부터 common.js는 templates 폴더 내의 여러 html 파일에서 공통적으로 사용될 함수들을 모아두는 JavaScript 파일이 될 것입니다.
📄index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/static/common.js"></script>
📄index.html
<body>
<div id="postingBox">
<select name='categories' id="categoryCode">
<option value='1'>Category 1</option>
<option value='2'>Category 2</option>
<option value='3'>Category 3</option>
</select>
<textarea id="postingBody"></textarea>
<button onclick="post_article()">Post</button>
<div>
</body>
📄common.js
function post_article() {
let post_body = $('#postingBody').val();
let category_code = $('#categoryCode').val();
$.ajax({
type: "POST",
url: "/api/postarticle",
data: {
'category_code_give': category_code,
'post_body_give': post_body
},
success: function (response) {
if (response['result'] == 'success') {
window.location.reload()
}
}
})
}
📄app.py
@app.route('/api/postarticle', methods=['POST'])
def post_article():
category_code_receive = request.form['category_code_give']
post_body_receive = request.form['post_body_give']
article = {
'category_code': category_code_receive,
'post_body': post_body_receive
}
db.articles.insert_one(article)
return jsonify({'result': 'success'})
다음은 Server DB에 저장한 data를 client로 불러오는 작업을 해보겠습니다.