我正在尝试使用 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>
无论我访问哪个 URL,只要它位于同一域中,似乎都会发生这种情况。我尝试传递一些数据,但这没有什么区别。
当然,我可以通过使用 get 函数来解决这个问题,就像我在第三个测试函数中所做的那样,但我仍然很好奇为什么会发生这种情况。
我知道有一个similar question在这里问,但它没有回答我的问题。
最佳答案
json 需要有效,否则回调将不会触发。
关于javascript - 在 jQuery 中使用 getJSON 函数时,回调函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/770381/