Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

django - jQuery.getJSON doesn't trigger callback

I have a html code:

<button>asd</button>
<script type = "text/javascript">
$('button').click(
    function() {
        $.getJSON('/schedule/test/', function(json) {
            alert('json: ' + json + ' ...');
        });
    }
);
</script>

and corresponding view:

def test(request):
    if request.method == 'GET':
        json = simplejson.dumps('hello world!')
        return HttpResponse(json, mimetype = 'application/json')

The view is executed (tested using print), json variable is initialised but no alert appears. What did I do wrong? I've already seen some docs on this (http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback for example) but I didn't find an answer.

EDIT: The problem was, that HttpResponse was not imported... Unfortunately Django gave no error about it. Everything else was correct. regards
chriss

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It is likely that the json is not properly formed. Sometimes this happens to me when my code, that should be producing json is generating an error. Two options:

  • Use firebug to view the JSON response

  • Setup error handling in your jquery code using the jQuery.ajaxSetup options such as:

      $.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) {   
          alert(textStatus);
          alert(errorThrown);
          alert(XMLHttpRequest.responseText);
      }});
    

Using the error handling for debugging is great, since you will know immediately when there is a problem with your response. You can check out the jQuery documentation for jQuery.ajax which has all of the available options for jQuery.ajaxSetup.

EDIT: A third option would be to just open the URL that should be generating the JSON and run the output through JSON Lint to validate it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...