【问题标题】:Display output with out refresh using Django, Ajax使用 Django、Ajax 显示不刷新的输出
【发布时间】:2018-02-10 10:29:57
【问题描述】:

我正在编写一个简单的基本计算器

  • 我从用户那里得到输入
  • 接受输入并进行计算
  • 并在同一页面上显示输出

我有一个基本的 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 模板并将其显示在输出字段中 一旦我点击同一页面上的提交按钮。

【问题讨论】:

    标签: python ajax django


    【解决方案1】:

    success() 函数中,您应该将结果附加到output 标记的innerHTML 并为输出标记提供一个id,可以从JS 函数访问

    【讨论】:

    • 我知道,但我的疑问是如何将我的视图中的结果传递给我的 HTML 模板
    • 您已经从视图发送了JSON 响应,您需要做的就是从您的AJAX 接收数据并将其注入函数,例如` $(#id).innerHTML (响应)`
    • 是的,但我的JsonResponse 没有结果。我的疑问是如何将我的结果附加到我的JsonResponse
    • 试试return JsonResponse({ "result" : value})
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2018-05-12
    相关资源
    最近更新 更多