问题描述
这是我第三次提出这个问题,很遗憾,没有专家可以回答这个简单的问题.
This is the third time I ask this question, unfortunately there is no expert who can answer this simple question.
如果没有javascript代码,view.py
中的方法对于保存和计算均适用,两个提交一个表单即可.但是,当我使用ajax时,它会失败(由于e.preventDefault();
),这是我的代码:
Without javascript code the method within view.py
works perfectly both for save and calc, two submit for one form. However when I use ajax, it fails (because of e.preventDefault();
), here is my code:
html
<form method="post" id="idForm" name="fmr1" action = "/myproject/save/"
enctype="multipart/form-data">
....
<input type="submit" name="save" value="Save">
<input type="submit" name="calc" value="Calculate">
</form>
js
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var frm = $('#idForm');
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data.mylist)
},
error: function (data) {
alert("ajax fails")
}
});
});
观看次数
if request.method == 'POST' and 'calc' in request.POST:
print("runs calc form")
mylist= [5]
return JsonResponse({'mylist':mylist})
问题
现在,问题出在request.POST中的'calc'"中,因此当我向表单添加ajax或id ="idForm"时,它无法运行.
Now the difficulty is in "'calc' in request.POST", so it does not run when I add ajax or id="idForm" to the form.
我还需要运行保存",因此我需要在request.POST中添加"calc".
I need "'calc' in request.POST" since I have to run "save" as well.
两者都必须在视图的一个方法中运行.
Both will have to run inside one method in views.
javascript(e.preventDefault();
)阻止其正常运行的原因可能是什么?
What can be the reason that javascript (e.preventDefault();
) prevents it from running correctly?
如何解决?
推荐答案
因为没有人回答这个问题.使用ajax时,两个按钮的一种形式不起作用,我使用了一个按钮和一个输入:
Since no one answered this question. With ajax two button one form did not work, I used one button and one input:
<input type="submit" name="save" id="save" value="Save">
<button type="button" onclick="sendData()">Calculate</button>
这对我有用.在视图中,我实现了两种方法.
this worked for me. In views I implemented two methods.
这篇关于在Django中,两个人以一种形式提交提交输入并在Ajax中提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!