list.html中有一个特定的按钮:
{% load static %}
...
{% include "execute.html" %}
...
<button type="button" id="id">Execute Script</button>
意见.py:
import subprocess
import os
...
def exec_com(request):
if request.is_ajax():
if request.method == 'POST':
command = request.POST['cmd']
os.chdir('../static/tools/')
return subprocess.call(command, shell=True)
return HttpResponseRedirect(reverse('list'))
网址.py:
url(r'^execute/$', views.exec_com, name='execute'),
执行.html:
{% load static %}
<script src="{% static 'js/jquery.cookie.min.js' %}"></script>
<script type="text/javascript">
$(document).on('ready', function(){
$('#id').on('click', function(){
data = {
"cmd": "id.py"
}
$.ajax({
headers: { "X-CSRFToken": $.cookie("csrftoken") },
url : window.location.href,
type: "POST",
data: data,
dataType: "text",
async: "asynchronous",
success: function(data) {
alert("Executed.")
console.log(data)
},
error: function(xhr,errmsg,err) {
alert("Something wrong.")
console.log(xhr.status + ": " + xhr.responseText)
}
});
});
});
</script>
单击时,脚本不执行。你能告诉我我错过了什么或做错了什么吗?
提前致谢。
您需要编写一个函数,该函数
python将在指定地址(url)处等待带有或不带有某些参数的请求并访问它。static没关系,是浏览器处理的,python脚本是解释器处理的。网址.py:
处理请求的函数
意见.py:
现在你可以从浏览器访问这个功能
http://localhost:port/get_for_url_name或者写相应的请求到JS应该管用 :)