我想使用 Ajax 从 Flask Web 应用程序中重启服务器。我的解决方案是在无限循环中遍历一个包含用于重新启动服务器的 .bat 文件的文件夹,并将每次循环的文件名发送给 Flask 函数。在 HTML 代码中,我使用 Jinja2 循环遍历文件,并创建指向 Ajax 调用的链接。
问题
我的 Ajax 代码有问题,它没有任何反应。
代码片段
@app.route('/restartajax/<computer>')
def restartajax(computer):
print 'code'
def runJob(computer):
try:
subprocess.call(r"\covenas\decisionsupport\meinzer\production\bat\restart%s" % computer)
except Exception,e:
print 'there was an exception', e
thr = Thread(target = runJob, args = [computer])
thr.start()
return jsonify(result=computer)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{url_for('static', filename='jquery.js') }}">\x3C/script>')</script>
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
<div class="col-md-12">
<div class="well well-lg">
<div class="container">
<h1>Restart a Computer or Server</h1>
<p>Clickit.</p>
{% for item in restartFiles %}
{% if 'Backup' not in item and 'dummy' not in item %}
<div class="col-md-4">
<script type=text/javascript>
$(function() {
$('a#calculate').bind('click', function() {
$.getJSON($SCRIPT_ROOT + '/restartajax/'+item, {
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
<h4>{{item}}</h4>
<span id=result>?</span>
<p><a href=# id=calculate>restart {{item}}</a>
</div>
{%endif%} {%endfor%}
2、解决方案
为了解决这个问题,我对代码进行了如下修改:
- 在 HTML 中,我使用了一个类 (
class="calculate") 而不是 ID (id) 来绑定 jQuery 监听器。 - 在 JavaScript 中,我使用
$(this).attr('id')来获取用户点击的元素的 ID,并将该 ID 传递给 Ajax 调用。
修改后的 HTML 代码如下:
{% for item in restartFiles %}
<div class="col-md-4">
<script type=text/javascript>
$(function() {
$('a.calculate').bind('click', function() {
var item = $(this).attr('id');
$.getJSON($SCRIPT_ROOT + '/restartajax/'+item, {
}, function(data) {
$("#result").text(data.result);
});
return false;
});
});
</script>
<h4>{{item}}</h4>
<span class="result">?</span>
<p><a href=# name = a class="calculate" id="{{ item }}">restart {{ item }}</a>
</div>
{%endif%} {%endfor%}
修改后的 JavaScript 代码如下:
$('a.calculate').bind('click', function() {
var item = $(this).attr('id');
$.getJSON ...
代码片段
@app.route('/restartajax/<computer>')
def restartajax(computer):
def runJob(computer):
try:
subprocess.call(r"\covenas\decisionsupport\meinzer\production\bat\restart%s" % computer)
except Exception,e:
print 'there was an exception', e
thr = Thread(target = runJob, args = [computer])
thr.start()
return jsonify(result=computer)