jQuery.getJSON不会触发回调 [英] jQuery.getJSON doesn't trigger callback
问题描述
我有一个html代码:
I have a html code:
<button>asd</button>
<script type = "text/javascript">
$('button').click(
function() {
$.getJSON('/schedule/test/', function(json) {
alert('json: ' + json + ' ...');
});
}
);
</script>
和相应的视图:
def test(request):
if request.method == 'GET':
json = simplejson.dumps('hello world!')
return HttpResponse(json, mimetype = 'application/json')
视图被执行(使用 print
), json
变量初始化,但不显示警报。我做错了什么?我已经看到一些文档( http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback ),但我没有找到一个答案。
编辑:问题是, HttpResponse
未导入...不幸的是Django没有给出错误它。一切都是正确的。
认为
chriss
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.
The problem was, that HttpResponse
was not imported... Unfortunately Django gave no error about it. Everything else was correct.
regards
chriss
推荐答案
很可能json没有正确的形成。有时这种情况发生在我身上,当我的代码,应该是生产json时会产生一个错误。两个选项:
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:
-
使用firebug查看JSON响应
Use firebug to view the JSON response
使用jQuery.ajaxSetup选项在jquery代码中设置错误处理,例如:
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);
}});
使用错误处理进行调试是非常好的,因为您在回答问题时立即知道。您可以查看 jQuery.ajax的jQuery文档,该文档具有所有可用选项jQuery.ajaxSetup。
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.
编辑:第三个选项是打开应该生成JSON的URL,并通过 JSON Lint 进行验证。
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.
这篇关于jQuery.getJSON不会触发回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!