小编典典

Django按钮ajax请点击

ajax

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

阅读 573

收藏
2020-07-26

共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>
2020-07-26