简体   繁体   English

如何在不刷新的情况下提交表单并显示output

[英]how to submit a form and display output without refreshing

I'm trying to create a simple calculator which gets an input number from the user and shows the calculated output below it.我正在尝试创建一个简单的计算器,它从用户那里获取输入数字,并在其下方显示计算得到的 output。 The code works fine but it redirects and reloads the page, obviously.该代码工作正常,但显然它重定向并重新加载页面。 I don't want that I want the output to be displayed as soon as the user fills the form.我不希望用户填写表格后立即显示 output。 I have 0 knowledge of js and ajax so I would appreciate you guys helping me with that part.我对 js 和 ajax 的了解为 0,所以我很感谢你们在这方面帮助我。 I searched a lot but couldn't understand what to do.我搜索了很多,但不知道该怎么做。 this is my form:这是我的表格:

<form id="myform" method="POST">
    {% csrf_token %}
    Enter first number: <input type="text" name="num1"><br><br>
    <input type="submit">
</form>

and this is the output bellow the form I want:这是 output 波纹管我想要的形式:

<h1>congrats!</h1>

as simple as that.就如此容易。 fill the form, submit and display a simple message without refreshing填写表单,提交并显示一条简单的消息,无需刷新

If you have zero knowledge and could not produce any code you will most likely face a lot of problem, AJAX vs Django form is another level of complexity and will not implement unless you are 100% sure that will add something to the UX, but in short.如果您的知识为零并且无法生成任何代码,您很可能会面临很多问题,AJAX 与 Django 形式是另一个复杂程度并且不会实现,除非您 100% 确定这会为 UX 添加一些东西,但在短的。

Using Jquery you could built an Ajax call to a Django view :使用 Jquery 您可以构建对Django 视图Ajax 调用

JS Script: JS脚本:

 $(document).ready(function () {
      $("form").submit(function (event) {
        var formData = {
          justification: $("#justification").val(),
          

        };
    
        $.ajax({
          type: "POST",
          url: "{% url 'django-view'  %}",
          data: formData,
          dataType: "json",
          encode: true,
        }).done(function (data) {
          
          if (data.success) {
            console.log("error");
    
         
          } else {
           # display your text somewhere in your page
          }
        });
    
        event.preventDefault();
      });
    });

Django View: Django 查看:

@csrf_exempt
def form_post(request):
    # Do something with your data
    text = request.POST.get("num1")
    print(text)
    return JsonResponse({"text": text})
 

As you can see you need a lot more to work with Ajax, you need a good understanding of Django form, a good enough one for Ajax and JS and finally how asynchronous works.正如您所看到的,您需要更多地使用 Ajax,您需要很好地理解 Django 形式,对于 Ajax 和 JS 来说已经足够好,最后是异步如何工作的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM