【问题标题】:Django button ajax clickDjango按钮ajax点击
【发布时间】:2012-11-23 21:37:00
【问题描述】:

我有一些 Django 渲染良好的 HTML。我想单击 HTML 上的一个按钮,并让它在视图中触发一个事件。

看起来该按钮不会导致post 触发。我不确定我做错了什么。

这是我的views.py 代码:

def log(request):
  if not request.POST:
    template = loader.get_template('log.html')
    html = template.render(Context())
    return HttpResponse(html)
  print "Post"

这是我的log.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
<script type="text/javascript">
    $("#update_log_button").bind("button", function(){
        $.post("hello");
        return false;
    });
</script>
</head>
<body>
<p>
    <span>SPHIINX Log</span>
</p>
<p>
    <textarea cols="2" name="log" rows="25"></textarea>
     <input id="update_log_button" name="update_log" type="button" value="Update Log"/>
</p>
</body>
</html>

【问题讨论】:

    标签: javascript html ajax django


    【解决方案1】:

    您不直接使用click 事件是否有原因?

    试试这个:

    <script type="text/javascript">
      $(function(){
        $("#update_log_button").click(function(){
            $.post(
             url : "/hello/",
             dataType:"html",
             success: function(data, status, xhr){
                //do something with your data
            }
            );
            return false;
        });
     });
    </script>
    

    如果按钮是动态创建的,那么您可能需要使用bind 函数将click 事件处理程序附加到元素:

    <script type="text/javascript">
       $(function(){
        $("#update_log_button").bind('click', function(){
            $.post(
             url : "/hello/",
             dataType:"html",
             success: function(data, status, xhr){
                //do something with your data
            }
            );
    
            return false;
        });
       });
    </script>
    

    试试这个 URL 来包含 JQuery 库:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    

    【讨论】:

    • 可能我没有改变答案...注意网址。更改为您正在使用的内容!
    • 这对我也不起作用。我敢肯定,这是我对 JS/AJAX 缺乏了解。
    • 让我的views.py响应来自.html的按钮点击的最简单方法是什么?
    • 当然,我得到:此页面上没有 Javascript 如果
    • 我猜你的脚本标签很好,但你的 jquery 库在哪里?
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 2015-04-25
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    相关资源
    最近更新 更多