JSON Results offered to be saved
I'm new to JSON and I'm just wondering why every time I try to pass results as JSON, the browser (Firefox) always offers me to save it as a local file? Is that the behavior of JSON? I thought it would be like passing XML that the browser will only show it. I'm 开发者_如何学Gobuilding the JSON using PHP:
header('Content-Type: application/json'); $json = "{\n"; $json .= " \"address\": \n"; $ctr = 0; $numrows = mysql_num_rows($result); while($row = mysql_fetch_array($result, MYSQL_ASSOC)){ $json .= " {\n"; $json .= " \"id\": \"". $row['id'] ."\",\n"; $json .= " \"lon\": \"". $row['lon'] ."\",\n"; $json .= " \"lat\": \"". $row['lat'] ."\",\n"; $json .= " \"road\": \"". $row['road'] ."\" \n"; $json .= " }"; $ctr++; $json .= ($ctr < $numrows) ? ",\n" : "\n" ; } $json .= "}"; echo $json;
JSON is not XML of course. If you omit the Content-type header or set it to e.g. text/plain the browser will render it. However, the current content-type is correct. Install the JSONView extension to be able to see json in the browser instead of getting a download window.
Besides that, NEVER EVER BUILD JSON USING STRING FUNCTIONS. PHP has json_encode()
which takes an object/array/.. and returns a valid JSON string. So your code should look like this:
header('Content-Type: application/json');
$rows = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$rows[] = $row;
}
echo json_encode($rows);
精彩评论