我正在使用Flask和ajax连接我的Javascript和Python脚本。目标是:在JSP中单击一个按钮后,应该触发Python脚本。使用我共享的代码,我可以在按下按钮时触发Python程序。但回应并没有被送回ajax。我尝试了各种选择,但我仍然无法完成它。
这是我的script.js
$.ajax({
type: "POST",
url: "http://127.0.0.1:5000/crawler",
data: {testUrl:testUrl},
dataType: 'json',
success: function(response) {
console.log(JSON.stringify(response))
alert(JSON.stringify(response))
},
failure: function(response) {
alert("failure")
}
});
这是我的python程序
from flask import Flask, request, jsonify
from selenium import webdriver
from q_learn import Q
from configparser import ConfigParser
app = Flask(__name__)
@app.route('/crawler', methods = ['POST'])
def new():
url = request.form['testUrl']
print('url is: ',url)
parser = ConfigParser()
parser.read('...Crawler\\config_prop\\config.ini')
path = parser.get('driver', 'executable_path')
driver = webdriver.Chrome(executable_path=path)
URL = url
q = Q(driver, URL)
obj = q.QLearn(0.8, 0.8, 0.01, 0.3, 5, 15)
print(obj)
driver.close()
return jsonify(obj)
if __name__ == "__main__":
app.run()
答案 0 :(得分:0)
试试这个: 脚本:
$.ajax({
type: "POST",
url: "http://127.0.0.1:5000/crawler",
data: {testUrl: testUrl},
dataType: 'json',
success: function (response) {
console.log(response.objt)
alert(JSON.stringify(response.objt))
},
failure: function (response) {
alert("failure")
}
});
烧瓶中:
from flask import Flask, request, jsonify
from selenium import webdriver
from q_learn import Q
from configparser import ConfigParser
app = Flask(__name__)
@app.route('/crawler', methods = ['POST'])
def crawler():
url = request.form.get('testUrl')
print('url is: ',url)
parser = ConfigParser()
parser.read('...Crawler\\config_prop\\config.ini')
path = parser.get('driver', 'executable_path')
driver = webdriver.Chrome(executable_path=path)
URL = url
q = Q(driver, URL)
obj = q.QLearn(0.8, 0.8, 0.01, 0.3, 5, 15)
print(obj)
driver.close()
return jsonify(objt=obj)
if __name__ == "__main__":
app.run()