我正试图将芹菜任务中的数据输出到一个单独的窗口中。我是JavaScript
和AJAX
的新手,这就是我当前的问题所在。在执行视图之后,启动芹菜任务,并呈现下一个html页面(success.html
(:
success.html
{% block content %}
<body>
{% if task_id %}
<h1>task_id has been called: {{ task_id }}</h1>
<script src="{% static 'MyAPP/bootstrap/js/task_output_retrieval.js' %}"></script>
<script type='text/javascript'> task_state("{{ task_id }}"); </script>
<script src="{% static 'MyAPP/bootstrap/js/update-hello-user.js' %}"></script>
<script type='text/javascript'> second(); </script>
<h1> END </h1>
{% endif %}
</body>
{% endblock content %}
我知道调用了JavaScript
,因为至少打开了一个窗口。这是.js
:
task_output_retrieval.js
function task_state (task_id) {
var taskID = task_id;
var newWin = window.open('', 'new window', 'width=200, height=100');
$.ajax({
url: '{% url validate_task_state %}',
data: {'taskID':taskID},
method: 'POST',
dataType : "json",
success: function(data){
$(newWin.document.body).html(data);
newWin.document.write(data);
newWin.document.close();
newWin.focus();
newWin.print();
newWin.close();
},
error: function (){ alert('An error occured'); }
});
}
task_state(task_id);
和url.py:
url(r'^ajax/task_state/$', task_state, name='validate_task_state'), # for ajax
和观点:
admin_scripts.py
def task_state(request):
print ("You reached the task_state function")
data = 'Fail'
task_id = request.GET.get('task_id')
#task_id = request.session['task_id']
try:
async_result = AsyncResult(task_id)
except KeyError:
ret = {'error':'No optimisation (or you may have disabled cookies).'}
return HttpResponse(json.dumps(ret))
print ("request.is_ajax(): {0}".format(request.is_ajax()))
if request.is_ajax():
if 'task_id' in request.POST.keys() and request.POST['task_id']:
task_id = request.POST['task_id']
async_result.get()
data = {
'state': async_result.state,
'result': async_result.result,
}
#data = async_result.result or async_result.state
print ("data: {0}".format(data))
else:
data = 'No task_id in the request'
else:
raise SuspiciousOperation("This is not an ajax request.")
json_data = json.dumps(data)
return HttpResponse(json_data, content_type='application/json')
task_state
中仍有许多悬而未决的问题,我不完全理解,通过反复尝试,我会解决的,但现在,task_state
还没有被调用。我怀疑问题出在AJAX调用("url"(上,但我不知道为什么。我哪里错了?
更新:选中"JS Test Stuff"复选框后,success.html
将被呈现,没有错误。AJAX JavaScript(task_output_retrieval.js
(是从success.html
中调用的,这一点得到了验证,因为我从success.html
调用了两个JavaScript文件(另一个是update-hello-user.js
(。打开task_output_retrieval.js
中的窗口,并显示update-hello-user.js
中的弹出窗口。它在task_output_retrieval.js中,我在其中调用视图:
$.ajax({
url: query_url,
)
但这并没有被渲染。
以下是控制台的输出:
[17/Aug/2018 04:59:12] INFO [django.server:124] "GET /MyApp/opt/ HTTP/1.1" 200 6631
async_result f2224e67-3e47-4980-9dc8-58622928e090
TASK_ID f2224e67-3e47-4980-9dc8-58622928e090
[17/Aug/2018 04:59:14] INFO [django.server:124] "POST /MyApp/opt/ HTTP/1.1" 200 6412
[17/Aug/2018 04:59:14] INFO [django.server:124] "GET /MyAppsite-static/MyApp/bootstrap/js/update-hello-user.js HTTP/1.1" 200 52
[17/Aug/2018 04:59:14] INFO [django.server:124] "GET /MyAppsite-static/MyApp/bootstrap/js/task_output_retrieval.js HTTP/1.1" 200 640
在查看您的代码时,我突然想到的问题是在JavaScript文件中使用{% url validate_task_state %}
。如果您按照最常见的推荐方法设置Django并提供其静态内容,则模板引擎将不会处理您的JavaScript文件,并且该模板标记也不会被处理。此外,它需要在其论点周围引用引号,因此{% 'url validate_task_state' %}
您应该更改success.html
模板,将所需的URL传递给task_state
函数,如下所示:
<script src="{% static 'MyAPP/bootstrap/js/task_output_retrieval.js' %}"></script>
<script type='text/javascript'> task_state("{% url 'validate_task_state' %}", "{{ task_id }}"); </script>
并修改您的函数以采用新的参数:
function task_state (query_url, task_id) {
var taskID = task_id;
var newWin = window.open('', 'new window', 'width=200, height=100');
$.ajax({
url: query_url,
data: {'taskID':taskID},
method: 'POST',
dataType : "json",
success: function(data){
$(newWin.document.body).html(data);
newWin.document.write(data);
newWin.document.close();
newWin.focus();
newWin.print();
newWin.close();
},
error: function (){ alert('An error occured'); }
});
}
您在评论中说Django没有看到请求。一个常见的问题是CSRF保护:自定义POST请求需要传递CSRF令牌,否则将被拒绝。如何做到这一点的细节部分取决于您的具体配置,但通常情况下,我会这样做:
// Grab the CSRF token from the cookie.
var csrftoken = $.cookie('csrftoken');
$.ajax({
type: "POST",
url: "... my url ...",
headers: {
// Pass the token with the query.
'X-CSRFToken': csrftoken
},
// other ajax options...
});