json - 使用 css 将 Jsonify 返回到 html 页面
问题描述
我目前正在开发一个处理用户登录的 FLASK 应用程序。它背后的想法是,当用户输入他的登录凭据时,表单会将他的信息发送到一个 API,该 API 将确定登录是否成功。API 将发送一条消息以显示它是否成功。API 和模板页面工作正常,我可以使用 jsonify 返回消息,但我想将 jsonify 数据返回到一个 html 页面,该页面具有我的 css 设计并扩展了我的“base.html”这是我到目前为止的内容:
我的登录 API
def index():
code, message = "ERROR", "Invalid Credentials"
loginid = str(request.form.get('id')) or ''
pw = str(request.form.get('pw')) or ''
if len(loginid) == 0 or len(pw) == 0:
# Fields not filled
message = "Please fill in all required fields"
return jsonify({"code": code, "message": message})
if get_user(loginid, pw):
# Authentication Sucessful
code, message = "OK", "Authentication successful."
regen_session()
session['auth'] = True
session['user'] = loginid
return jsonify({"code": code, "message": message})
# User credentials error
return jsonify({"code": code, "message": message})
有人可以告诉我如何将 jsonify 对象返回到包含我的 html 和 css 的页面吗?谢谢您的帮助。
解决方案
我总是使用 JSON dataType 在客户端和服务器之间使用 javascript 进行通信。
我在这里提供工作示例:
HTML部分和jquery ajax:
<input type="text" id="id_field">
<input type="password" id="pass_field">
<button type="button" onclick="sendData()">ok</button>
<script>
function sendData (){
var get_id = document.getElementById("id_field").value
var get_pass = document.getElementById("pass_field").value
$.ajax({
type: "POST",
url: "{{url_for('index')}}",
data: JSON.stringify({id: get_id,pw: get_pass}),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data){
//handle response here
},
error: function(data){
//handle errors here
}
});
}
</script>
烧瓶部分:
@app.route('/index', methods=['POST'])
def index():
if request.method == 'POST':
loginid = request.json.get('id')
pw = request.json.get('pw')
# do whatever with data then return jsonify data to ajax function
return jsonify({"code": code, "message": message})
推荐阅读
- cygwin - cygwin rbenv ruby-build 损坏的 irb 用于多个版本
- python - 如何将我的主窗口链接到一个对话框,以便当我选择 File -> New 时,我的“新事物”对话框打开?
- sql - 谷歌表格查询功能。我怎样才能只获得唯一或不同的行?
- macos - 如何在 Mac 上更改智能文件夹中的搜索范围?
- docker - 如何连接到在 Docker 上运行的 Rust 服务器应用程序
- ruby-on-rails - Rails ActiveRecord 返回与数据库不同的结果
- assembly - 这里的正确语法是什么?
- node.js - Nodejs `crypto.publicEncrypt` 不会使用 `ssh-keygen rsa` 生成的公钥
- mysql - 如何优化mysql中的巨大左连接?
- javascript - 禁用类似媒体查询的 javascript