向 django 发送 ajax 请求并更新 html
Send ajax request to django and update html
我正在用 Django 编写一个 Web 应用程序,通过 ajax POST
请求在服务器上执行一些用 python 编写的代码,并且应该在客户端检索输出为a JSON 并用 javascript 部分更新 HTML。我可以将请求发送到服务器并执行子进程,我也可以检索 JSON 数据但未在 HTML 中更新但显示为没有 HTML 内容的网站字典.所以最后一部分不起作用,当我在视图函数中测试它时,我发现对于 ajax 请求它 returns false。另一个问题是子进程有一个文件作为输出,所以我无法从子进程中捕获标准输出
view.py:
def call(request):
call_form = Call(request.POST)
print(request.is_ajax())->returns false?
if call_form.is_valid():
purity_arg = call_form.cleaned_data['purity']
chr_sex = call_form.cleaned_data['chromosomal_sex']
command = "cnvkit.py call -m clonal --purity %s --drop-low-coverage %s" % ( purity_arg, chr_sex)
process_call = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,cwd=sfs.path('cnv_app/call_CNS/'), universal_newlines=True)
stdout, stderr = process_call.communicate()
if process_call.returncode and stderr:
output_call += stdout + '\n'
output_err_call += stderr + '\n'
else:
output_call += stdout + '\n'
process_call.poll()
response = {'output_call': output_call, 'output_err_call': output_err_call}
return JsonResponse(response)
.html:
<h2>Call</h2>
<p>Given segmented log2 ratio estimates (.cns), derive each segment’s absolute integer copy number using either:</p>
{% if call_form %}
<form enctype="multipart/form-data" method="POST" id="post-form" >
{% csrf_token %}
{{call_form|crispy}}
<button type="submit" name="call_submit_button" value="submit">Submit</button>
</form>
{% endif %}
<div id="response_msg"></div>
<script src="{% static 'js/jquery-3.5.1.min.js' %}"></script>
<script src="{% static 'js/js_script_main.js' %}"></script>
urls.py
urlpatterns = [
path('home/', views.home, name='home'),
path('cnvPipeline/', views.pipeline, name='cnvkit_pipeline'),
]
.js
$('#post-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url: '',
type: 'POST',
data: $(this).serialize(), //{'purity': '0.9', 'chromosomal_sex': 'X'},
dataType: 'json',
success: function (data) {
$(#response_msg).prepend(data.output_call)
}
});
});
我可以自己找到解决方案,我遵循了本教程:https://realpython.com/django-and-ajax-form-submissions/ 最后我发出了第一个异步请求。
.js
function send_call() {
$.ajax({
url: '/ajax_call/',
type : "POST", // http method
data : { "purity" : $('#purity-text').val(), "chromosomal_sex" : $('#chr-sex').val() }, // data sent with the post request
dataType: 'json',
// handle a successful response
success : function(json) {
$('#purity-text').val(''); // remove the value from the input
$("#results").prepend("<li>"+json.output_call+"</li><li> "+json.output_err_call+"</li>");
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
send_call()
});
forms.py
class Call(forms.Form):
purity = forms.DecimalField(widget=forms.NumberInput(attrs={'id':'purity-text'}))
chromosomal_sex = forms.ChoiceField(widget=forms.Select(attrs={'id':'chr-sex'}), choices=Sex_CHOICES, label='Chromosomal sex')
urls.py
path('ajax_call/', views.call, name='ajax_call')
views.py
def call(request):
call_form = Call(request.POST)
print(request.is_ajax())
if call_form.is_valid():
purity_arg = call_form.cleaned_data['purity']
chr_sex = call_form.cleaned_data['chromosomal_sex']
command = "cnvkit.py call -m clonal --purity %s --drop-low-coverage %s -o %s" % (purity_arg, sex_arg)
process_call = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=sfs.path('cnv_app/call_CNS/'), universal_newlines=True)
stdout, stderr = process_call.communicate()
#if process_call.returncode and stderr:
output_call = stdout + '\n'
output_err_call = stderr + '\n'
process_call.poll()
response_data = {'output_call': output_call, 'output_err_call': output_err_call}
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
.html
{% if call_form %}
<form enctype="multipart/form-data" method="POST" id="post-form" >
{% csrf_token %}
{{call_form|crispy}}
<button type="submit" value="submit">Submit</button>
</form>
{% endif %}
<div id="results"></div>
还是谢谢你!
我正在用 Django 编写一个 Web 应用程序,通过 ajax POST
请求在服务器上执行一些用 python 编写的代码,并且应该在客户端检索输出为a JSON 并用 javascript 部分更新 HTML。我可以将请求发送到服务器并执行子进程,我也可以检索 JSON 数据但未在 HTML 中更新但显示为没有 HTML 内容的网站字典.所以最后一部分不起作用,当我在视图函数中测试它时,我发现对于 ajax 请求它 returns false。另一个问题是子进程有一个文件作为输出,所以我无法从子进程中捕获标准输出
view.py:
def call(request):
call_form = Call(request.POST)
print(request.is_ajax())->returns false?
if call_form.is_valid():
purity_arg = call_form.cleaned_data['purity']
chr_sex = call_form.cleaned_data['chromosomal_sex']
command = "cnvkit.py call -m clonal --purity %s --drop-low-coverage %s" % ( purity_arg, chr_sex)
process_call = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,cwd=sfs.path('cnv_app/call_CNS/'), universal_newlines=True)
stdout, stderr = process_call.communicate()
if process_call.returncode and stderr:
output_call += stdout + '\n'
output_err_call += stderr + '\n'
else:
output_call += stdout + '\n'
process_call.poll()
response = {'output_call': output_call, 'output_err_call': output_err_call}
return JsonResponse(response)
.html:
<h2>Call</h2>
<p>Given segmented log2 ratio estimates (.cns), derive each segment’s absolute integer copy number using either:</p>
{% if call_form %}
<form enctype="multipart/form-data" method="POST" id="post-form" >
{% csrf_token %}
{{call_form|crispy}}
<button type="submit" name="call_submit_button" value="submit">Submit</button>
</form>
{% endif %}
<div id="response_msg"></div>
<script src="{% static 'js/jquery-3.5.1.min.js' %}"></script>
<script src="{% static 'js/js_script_main.js' %}"></script>
urls.py
urlpatterns = [
path('home/', views.home, name='home'),
path('cnvPipeline/', views.pipeline, name='cnvkit_pipeline'),
]
.js
$('#post-form').on('submit', function(event){
event.preventDefault();
$.ajax({
url: '',
type: 'POST',
data: $(this).serialize(), //{'purity': '0.9', 'chromosomal_sex': 'X'},
dataType: 'json',
success: function (data) {
$(#response_msg).prepend(data.output_call)
}
});
});
我可以自己找到解决方案,我遵循了本教程:https://realpython.com/django-and-ajax-form-submissions/ 最后我发出了第一个异步请求。
.js
function send_call() {
$.ajax({
url: '/ajax_call/',
type : "POST", // http method
data : { "purity" : $('#purity-text').val(), "chromosomal_sex" : $('#chr-sex').val() }, // data sent with the post request
dataType: 'json',
// handle a successful response
success : function(json) {
$('#purity-text').val(''); // remove the value from the input
$("#results").prepend("<li>"+json.output_call+"</li><li> "+json.output_err_call+"</li>");
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>×</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
};
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
send_call()
});
forms.py
class Call(forms.Form):
purity = forms.DecimalField(widget=forms.NumberInput(attrs={'id':'purity-text'}))
chromosomal_sex = forms.ChoiceField(widget=forms.Select(attrs={'id':'chr-sex'}), choices=Sex_CHOICES, label='Chromosomal sex')
urls.py
path('ajax_call/', views.call, name='ajax_call')
views.py
def call(request):
call_form = Call(request.POST)
print(request.is_ajax())
if call_form.is_valid():
purity_arg = call_form.cleaned_data['purity']
chr_sex = call_form.cleaned_data['chromosomal_sex']
command = "cnvkit.py call -m clonal --purity %s --drop-low-coverage %s -o %s" % (purity_arg, sex_arg)
process_call = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd=sfs.path('cnv_app/call_CNS/'), universal_newlines=True)
stdout, stderr = process_call.communicate()
#if process_call.returncode and stderr:
output_call = stdout + '\n'
output_err_call = stderr + '\n'
process_call.poll()
response_data = {'output_call': output_call, 'output_err_call': output_err_call}
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
.html
{% if call_form %}
<form enctype="multipart/form-data" method="POST" id="post-form" >
{% csrf_token %}
{{call_form|crispy}}
<button type="submit" value="submit">Submit</button>
</form>
{% endif %}
<div id="results"></div>
还是谢谢你!