我正在编写一个简单的基本计算器
我有一个基本的HTML表单
<form id="html_calc_form" action={%url 'calculation' %} method="post">
{% csrf_token %}
First Number:<br>
<input type="number" name="first number" value="0">
<br>
Second Number:<br>
<input type="number" name="second number" value="0">
<br>
Operation:<br>
<select name="operation" multiple>
<option value="Addition">Addition</option>
<option value="Subraction">Subraction</option>
<option value="Muntiplication">Muntiplication</option>
<option value="Division">Division</option>
</select>
<br><br>
<input type="submit" name "submit" value="Submit">
<output name="result" ></output>
</form>
防止刷新页面的Ajax逻辑
$(document).ready(function(){
$('#html_calc_form').submit(function(event){
console.log(event);
event.preventDefault()
$.ajax({
url:'calc/',
type:'POST',
data:$(this).serialize(),
success:function(response){
console.log(response);
$('form')[0].reset();
}
});
})
})
在django我创建了一个模型
class Calculation(models.Model):
first_digit = models.DecimalField(max_digits=7, decimal_places=3)
second_digit = models.DecimalField(max_digits=7, decimal_places=3)
CALCULATION_CHOICE = (('+', 'Addition'),
('-', 'Subraction'),
('*', 'Muntiplication'),
('/', 'Division'))
calculate = models.CharField(max_length=1, choices=CALCULATION_CHOICE)
最后我的观点
def calc(request):
if request.method == 'POST':
first_number = request.POST['first number']
second_number = request.POST['second number']
operation = request.POST['operation']
result = do_calc(operation, first_number, second_number)
# how to pass the result to my tempelate
value = Calculation.objects.create(
first_digit=first_number,
second_digit=second_number,
calculate=operation
)
return JsonResponse(model_to_dict(value))
def index(request):
return render(request, 'calculation/calculator.html')
我想将结果传递给我的HTML模板并将其显示在输出字段中 一旦我点击同一页面上的提交按钮。
答案 0 :(得分:0)
在success()
函数中,您应该将结果附加到output
标记的innerHTML,并为输出标记提供可以从JS函数访问的id