getJSON callback not happening
I have looked at similar queries here, but I can't seem to apply them to my problem. I am pretty new to jquery, so I may be doing something dumb. I have a simple getJSON test:
$(document).ready(function() {
$(".testurl").click(function() {
// do a json call
var url="testjson.php";
var rc=$.getJSON(
url,
{parm1: "P1", parm2: "P2", parm3: "P3"},
function(data){
alert("callback function inline");
});
var x = 1;
});
});
that calls a really simple script:
header("Content-Type: application/json");
echo "{\"results\": [";
$arr = array();
$arr[] = "{\"fld1\": \"result1\", \"fld2\": \"result2\", \"fld3\": \"result3\"}";
echo implode(", ", $arr);
echo "]}";
that returns valid JSON (I checked on JSON lin开发者_JAVA技巧t)
The var rc that I use to receive the result of the request has the following values:
getResponseText \"{\"results\": [{\"fld1\": \"result1\", \"fld2\": \"result2\", \"fld3\": \"result3\"}]}\""
getReadyState 4
getStatus 200
Why does the callback function not fire?
If the click handler is attached to an anchor element then maybe the ajax call doesn't have time to execute before redirecting to a different page. Try adding a return false
to the click callback:
$(".testurl").click(function() {
// do a json call
// ...
return false;
});
The $.getJSON call is just assigned to a variable, it is not being called.
精彩评论