Why is my $.getJSON response data null?
I have a very simple setup that I can't seem to get working. I have a simple PHP page that just starts a session and is supposed to output the status and the session id in JSON. However, when the ajax call returns, the data is always null. I'm using Firebug, and I can see the ajax function calling my callback.
Here's the PHP page on the server:
<?php
try
{
if(!session_开发者_Python百科start()) {
throw new Exception("unable to start session");
}
echo json_encode(array(
"status" => "success",
"session_id" => session_id()
));
}
catch(Exception $e)
{
echo json_encode(array(
"status" => "fail",
"error" => $e->getMessage()
));
}
?>
It works fine and outputs something like this:
{"status":"success","session_id":"i3cdogb9jgd6oudar104qfuih1"}
The HTML page is just as simple:
<html>
<head>
<script src="jquery-1.4.1.min.js" type="text/javascript"></script>
<title>getJSON example</title>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "http://webserver/init.php",
dataType: 'json',
success: function(json) {
if(json.status === "success"){
$("#session_key").val(json.session_id);
}
}
});
});
</script>
</head>
<body>
<input type="hidden" id="session_key"/>
</body>
</html>
Additional Information
Request Headers:
GET /init.php HTTP/1.1
Host: ir-6483
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: null
Response Headers:
HTTP/1.1 200 OK
Date: Mon, 01 Feb 2010 16:50:11 GMT
Server: Apache/2.2.14 (Win32) PHP/5.2.12
X-Powered-By: PHP/5.2.12
Set-Cookie: PHPSESSID=i033rd4618o18h3p5kenspcc35; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 101
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
So, you can see the PHP session ID is being set, but the response tab is empty.
I think I've found the problem (skip to the bold text for the short answer).
I tried the example on my machine by creating an .html file on my desktop and uploading the PHP snippet to my dev server on the LAN. This gave me the exact same results as you, also with Firefox (v3.5.7).
I'm not a PHP guy (more Python / Django) but I do know some basic PHP and your code looked fine to me. I confirmed this with much Googling of PHP / JSON / Ajax example-seeking. I tried every option given in advice forums, including various caching header options in the PHP and different JQuery methods, including changing some of its cache options and also trying various different options. No difference.
I completely simplified the PHP to literally just return a single-item JSON array, without any other conditionals or control structures - no joy.
Eventually I got desperate and tried the same file in IE 8. It worked! Tried it in Safari - it worked!
I then got paranoid and thought there might be some sticky session issues in Firefox or some other oddity so I completely cleared my Firefox history and restarted the browser. No difference.
This at least gave me a different angle on what I could Google for to see if others had the same problem. Indeed they had.
It turns out that if you are running the HTML file containing the Ajax on your local machine, i.e. with a "file://" prefix, Firefox for some reason will not make the Ajax calls correctly. I copied the file up to my dev server, in the same location as the PHP file (but still using the full address as the Ajax URL) and sure enough it worked!
I don't fully understand what Firefox does differently with truly local files and Ajax, but it's getting light outside and I can't investigate right now. I did look through the settings regarding security but nothing obvious jumped out at me. I'd be very interested to know how this fits into how your dev environment is set up. I will investigate further later if I get a chance and will update this answer.
I wouldn't be surprised if there is some or other option in "about:config" that may contain the answer.
I copied the HTML and Javascript from your example, changing only the invocation of init.php to simply 'init.php' (fully assuming same server and directory), and the example worked perfectly. There is nothing inherently wrong with the posted code, which means you need to double check the Firebug net tab to see what request is being made and what the response is. Also change the input type from hidden to text until you're sure everything is working. If you're using "View Source" to look for the resulting value, you won't see it, because the value did not exist when the page was loaded. If you have the Firefox Web Developer plugin installed, you can "View Generated Source", which will show the AJAX results in your hidden variable.
At the risk of getting flogged, you don't seem to have included jQuery.js in your document HEAD:
<script type="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
EDIT:
I would try setting a Content-Type header before outputting from the server, just in case:
header('Content-type: application/json');
精彩评论