我正在尝试运行一些通过Flask提供的python代码,我希望该python代码将值返回给javascript,以便我可以在其中使用它。
在这种情况下,我在HTML中有一个按钮,当我点击它时,我要运行python代码(通过Flask提供),并且它应该返回“ Hello”,我可以在HTML中使用它,例如显示或存储它它是另一个变量。
这是我的代码:
ajax.html
<!doctype html>
<html>
<head>
<title>country</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<button id="btn" onclick="flaskcall()">display</button>
<p id="display-here">Display here {{ temp }}</p>
<script>
function flaskcall()
{
$.ajax(
{
type: "POST",
url: "/hello",
dataType: "html",
success: function(msg)
{
console.log(msg);
$("#display-here").html(msg);
},
error: function (xhr, status, error) {
console.log(error);
}
});
}
</script>
</body>
</html>
flaskajax.py
from flask import Flask
app = Flask(__name__)
@app.route("/hello", methods=['GET', 'POST'])
def Hello():
message = "Hello"
return render_template("ajax.html", temp=message)
if __name__ == '__main__':
app.run(debug=True)
webserver.py
import SimpleHTTPServer
import SocketServer
PORT = 8888
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
我正在做的是,我正在运行webserver.py
,然后导航到http://localhost:8888/ajax.html
,当我按下display
按钮时,我看到了此错误
我什至不知道是否以正确的方式进行操作,我也不了解GET和POST方法。如果有人了解我实际上正在尝试做的事情,并且如果他们可以向我解释幕后的真实情况,我将不胜感激。如果您需要任何其他信息,请发表评论。
答案 0 :(得分:0)
这是您使用烧瓶的第二台服务器:
from flask import Flask, Response
app = Flask(__name__)
@app.route("/ajax")
def Hello():
resp = Response("Hello")
resp.headers['Access-Control-Allow-Origin'] = '*'
return resp
if __name__ == '__main__':
app.run(debug=True)
至关重要的是,如图所示设置标头,否则浏览器将不允许AJAX请求,因为它是到另一台服务器的。
现在在您的index.html
中将其放在<body>
中
<h1>Hello from Flask.</h1>
<button id="btn" onclick="flaskcall()">display</button>
<p id="display-here"></p>
<script>
function flaskcall() {
fetch("//localhost:5000/ajax").then(res => res.text()).then(res => {
document.querySelector("#display-here").textContent = res;
});
}
</script>
该函数将使用AJAX向烧瓶服务器请求GET /ajax
,服务器将向其回复Hello
。
然后将响应插入到文档中(为了安全起见,请使用非jQuery版本)。
答案 1 :(得分:0)
您似乎正在运行webserver.py,它与Flask应用程序无关。
您应将其运行为:
python flaskajax.py
它将运行自己的网络服务器,并使用默认的5000进行监听,您可以浏览到http://localhost:5000/hello
尽管您的代码存在一些问题,但是您忘记导入render_template。这应该是这样,
from flask import Flask
from flask import render_template
app = Flask(__name__)
@app.route("/hello", methods=['GET', 'POST'])
def Hello():
message = "Hello"
return render_template("ajax.html", temp=message)
if __name__ == '__main__':
app.run(debug=True)