开发者

$.getJSON not worked inside $('# ').click(function()

开发者 https://www.devze.com 2023-04-11 15:38 出处:网络
am new to jquery.I am doing some ajax using jquery in django. $(document).ready(function() { $.getJSON(\'/jsonserver/\', function(json){

am new to jquery.I am doing some ajax using jquery in django.

$(document).ready(function() {
     $.getJSON('/jsonserver/', function(json){
    alert("JSON Data: " + json);
    });

The above jquery worked for me. When I put the same in click function a button,it calling the url successfully ,But alert doesn't display.

   $(document).ready(function() {
          $('#save').click(function(){          
           $.getJSON('/jsonserver/', function(json){
            alert("JSON Data: " + json);
                });

          });开发者_StackOverflow中文版   
    });
<form method ="POST" method =/jqueryserver/ name ="form1" id ="form1">
    <input type= "submit" id = "save" name ="save" value ="Save" />
</form>

view.py

def jsonserver(request):
    print "...jsonserver..."
    json = simplejson.dumps('hello world!')
    return HttpResponse(json, mimetype = 'application/json')


Since $("#save") is a submit button, clicking that button is going to submit the form, and refresh the page.

What you want to do is "hijack" that by preventing the browser's default events from firing.

That can be done like this:

$('#save').click(function(e) {
   e.preventDefault();
   $.getJSON('/jsonserver/', function(json){
      alert("JSON Data: " + json);
   });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消