3

我有一些 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>
4

1 回答 1

3

是否有原因为什么您不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>
于 2012-12-05T22:42:41.887 回答