【问题标题】:a very simple ajax post and print in html with django一个非常简单的 ajax 帖子并使用 django 以 html 打印
【发布时间】:2014-08-25 01:03:08
【问题描述】:

我想在文本框中输入数字,我想得到所有的偶数。我知道这甚至可以使用 javascript 来实现,但我想用 djano 学习 ajax。所以这是我的看法

load_template

@csrf_exempt
def load_template(request):


    if request.method == 'POST':

        num1 =  request.POST['txt1']
        even_num = []

        for n in range(1, int(num1)+1):
             t = n%2
             if t == 0:
                  even_num.append(n)


         return HttpResponse(json.dumps(even_num) , content_type="application/json")

    else :

         return render (request , 'alongjs/index.html')

我的index.html

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/html">
    <body>

    <p> Even numbers </p>

    <!-- <form action="/jsdemo/alongjs/" method="post"> -->

    <form method='post' id ='test'>

         <input type="text" name="txt1"> </input>
         <input type='submit' value='Test button'/>

        <div id = 'message'>Answer: </div>


    </form>


    <script>


        $(document).ready(function() {

            var mes = document.getElementById('message');

           $("#test").submit(function(event){
                $.ajax({

                     type:"POST",
                     url:"/jsdemo/alongjs/",
                     data: {},
                     success: function(data){
                         mes.value = data
                     }
                });
                return false;
           });

        });

    </script>

    </body>
    </html>

我希望答案来自Answer :div。但页面正在刷新。

以及如何使用上述方法在 html 中使用以下格式呈现页面:

in index.html

   {% for num in even_nums %}
        {% num %}
   {% endfor %}

我是 ajax 新手,我知道我的 ajax post 不对,请指教。

【问题讨论】:

  • 尝试插入 event.preventDefault();在 ajax 调用之前。
  • 谢谢,我的大部分人现在都在工作,在返回 json 值后,如何使用 for 循环将其填充为列表。
  • 好的,我已经发布了回复作为答案。

标签: javascript jquery html ajax django


【解决方案1】:
$(document).ready(function() {

    var mes = $('#message');

    $("#test").submit(function(event){

        event.preventDefault(); 

        $.ajax({
            type:"POST",
            url:"/jsdemo/alongjs/",
            data: {},
            success: function(data){
                $.each(data, function(i, s){
                    $(mes).append(" " + s);
                });
            }
        });
        return false;
    });
});

【讨论】:

    猜你喜欢
    • 2012-10-17
    • 2012-05-15
    • 2012-10-02
    • 2021-06-13
    • 2012-06-15
    • 2018-03-15
    • 1970-01-01
    • 2014-07-06
    • 2018-10-25
    相关资源
    最近更新 更多