![](/img/trans.png)
[英]How can I control the flow of using JavaScript first and then send the control to the back end server created using flask framework?
[英]How can i send a JavaScript variable back to flask?
我正在尝试将“ip”变量从 home.html 发送到我的主 app.py python 文件,我尝试了很多东西,但都没有奏效,这是我正在使用的:
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$.getJSON("https://api.ipify.org?format=json",
function(data) {
var ip = data.ip
console.log(ip)
})
</script>
@app.route("/ip", methods=["GET", "POST"])
def get_ip():
return render_template('home.html')
我得到了它的工作,:这是答案:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON("https://api.ipify.org?format=json",
function(data) {
ip = data.ip
dd = {'ip': ip}
// console.log(ip);
// console.log(dd);
$.ajax({
data: JSON.stringify(dd),
contentType: "application/json; charset=utf-8",
dataType: "json",
type : 'POST',
url : '/'
})
});
})
</script>
如果您只想将 IP 发送到后端,请执行以下操作。 在 JS 中:
$.ajax({
dataType: 'string',
url: '/',
data: {
ip: '2.2.2.2'
},
type: 'GET',
success: function (data) {
...
...
}
});
并且,要接收 Flask 中的 IP,
ip = request.args.get("ip")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.