在jQuery中使用getJSON函数时,回调函数不起作用

Eli*_*ria 18 javascript ajax jquery

我试图在jQuery中使用getJSON函数来导入一些数据并触发回调函数.回调函数不运行.但是,如果我使用get函数尝试相同的操作,它可以正常工作.奇怪的是,即使我将"json"作为类型传递,它也适用于get函数.为什么会这样?我在Firefox 3和IE 7中测试了以下文件:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<title>ajax test</title>
<script type="text/javascript" src="/jquery-1.3.2.min.js"></script>
</head>
<body>
<input type="button" id="test1" value="get">
<input type="button" id="test2" value="getJSON">
<input type="button" id="test3" value="get with json type">
<script type="text/javascript">
$("#test1").click(function() {
    $.get("index.html",
        function(response) {
            alert('hi');
            //works
        }
    )
});

$("#test2").click(function() {
    $.getJSON("index.html",
        function(response) {
            alert('hi');
            //doesn't work
        }
    )
});

$("#test3").click(function() {
    $.get("index.html",
        function(response) {
            alert('hi');
            //works
        },
        "json"
    )
});
</script>
</body></html>
Run Code Online (Sandbox Code Playgroud)

无论我访问哪个URL,这似乎都会发生,只要它在同一个域上.我尝试传递一些数据,这没有什么区别.

当然,我可以通过使用get函数解决问题,就像我在第3次测试函数中所做的那样,但我仍然很好奇为什么会发生这种情况.

我知道这里有一个类似的问题,但它没有回答我的问题.

kar*_*m79 24

json需要有效,否则回调不会触发.

  • 这是令人难以置信的事情之一 - 它为什么会默默地失败?但这绝对是真的.http://www.jsonlint.com/是一个很好的验证器. (5认同)