问题
I am using this simple code to print an array as a JSON structure.
header('Content-Type: application/json');
echo json_encode($this->data, JSON_PRETTY_PRINT);
I'm using Chrome Version 28.0.1500.95 m. For some odd reason the output is wrapped in a pre tag with a tab character (i.e. \t
) at the beginning.
JSON seems to be parsing okay but I still get that tab character when no data is sent. How can I fix this ?
<pre style="word-wrap: break-word; white-space: pre-wrap;"> {
"title": "Node",
"items": [
{
"label": "Do stuff",
"icon": "..\/ui\/images\/icons\/16x16\/icon.png",
"action": "dostuff"
}
]
}</pre>
Edit: Here's the code on the jQuery side:
$.ajax({
url : "/myproject/getmenu/",
type : 'GET',
dataType: "json",
success : function(data) {
//alert(JSON.stringify(data,undefined,2));
if (jQuery.isEmptyObject(data)) {
return;
}
title = data.title;
items = data.items;
selected.contextPopup({
title : title,
items : items
});
}
});
回答1:
You need to remove whatever code adds the <pre>
tag. This causes your response to be invalid JSON (the whitespace to prettyprint it is not a problem though) and thus makes jQuery fail when parsing it.
I couldn't see anything in the PHP docs about the JSON response being wrapped in <pre>
but you could surely try it without the flag. I'd also make sure to check if the tag is actually in your response. If you use view-source and have a JSON-pretty-printing browser extension installed it might be added by that extension and not be in the actual JSON handled by your JavaScript code.
回答2:
hmmm,I was searching for an correct answer my self but none of them worked for. but I tried to do as following and it worked for me ...
1- I set the content type to application/json
2- I used the
die(json_encode($this->data))
instead of echo json_encode($this->data)
hope it will work for you although I guess its a bit too late :D forgive me for answering an old question I recently run into same issue myself
来源:https://stackoverflow.com/questions/18411670/tab-and-pre-wrapped-around-json-output-in-chrome