jQuery中使用的getJSON功能时,回调函数不工作

问题描述:

我想使用的getJSON函数jQuery中输入一些数据,并触发一个回调函数。回调函数不运行。但是,如果我尝试同样的事情get函数,它工作正常。奇怪的是,它与get函数的工作原理,甚至当我通过JSON作为类型。这究竟是为什么?我在Firefox 3测试了以下文件和IE 7:

I am trying to use the getJSON function in jQuery to import some data and trigger a callback function. The callback function doesn't run. However, if I try the same thing with the get function, it works fine. Strangely, it works with the get function even when I pass "json" as the type. Why is this happening? I tested the following file in Firefox 3 and 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,只要它是在同一个域。我试图通过一些数据,并没有发挥作用。

This seems to happen no matter what URL I access, as long as it's on the same domain. I tried passing some data and that doesn't make a difference.

当然,我可以解决的问题,通过使用get函数就像我在我的第三个测试功能做了,但我仍然好奇,为什么发生这种情况。

Of course I can work around the problem by using the get function like I did in my 3rd test function, but I am still curious as to why this is happening.

我知道有一个类似的问题要求在这里,但没有回答我的问题。

I know there is a similar question asked here but it didn't answer my question.

JSON的必须是有效的,否则回调将不会触发。

The json needs to be valid, otherwise the callback will not fire.