Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - Django button ajax click

I have some HTML that Django is rendering well. I'd like to click a button on the HTML and have that cause an event to fire in the view.

It doesn't look like the button is causing the post to fire. I'm not sure what I'm doing wrong.

This is my views.py code:

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

This is my 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is there a reason Why you are not using the click event directly?

Try this:

<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>

If the button is dynamically created then you may want to use the bind function to attach click event handler to the element:

<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>

Try this URL to include the JQuery library:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

2.1m questions

2.1m answers

60 comments

56.8k users

...