Can you retrieve json data without it being json_encoded in php?
I am not having any luck but i was wondering if i could grab json dat开发者_StackOverflow社区a if it is not json encoded server side with php. for example if i were to just echo some data like so:
echo '{"subscriptions": [{"subscribe":"'.$subscribe[0].'"},{"subscribe":"'.$subscribe[1].'"},{"subscribe":"'.$subscribe[2].'"},{"subscribe":"'.$subscribe[3].'"},{"subscribe":"'.$subscribe[4].'"}]}';
could i still use a jQuery ajax json call to grab the data?
That certainly looks ok and should work just fine.
json_encode()
only makes the process easier as it'd be pretty easy to make a quoting / bracket / brace / square-bracket error when creating the string manually.
I'm guessing you're only asking as json_encode()
is not available on your server. As an alternative, you could try the component from Zend Framework. This attempts to use json_encode()
but falls back to a built-in approach when not available.
See http://framework.zend.com/manual/en/zend.json.html
Yes, as long as the echo'd data is valid JSON data
Essentially all that is happening is you are creating a JSON format and creating your own encoder. But you will need to post your own JSON headers as well. Start your callback PHP file with:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
Remember that you will need to take special attention to formatting your JSON otherwise it will break your application.
I believe as long as you send our the proper server header indicating it's JSON content Content-Type: application/json
it should be good.
Whats wrong with using PHP's json_encode()
? Are you working with an older version of PHP?
You can, but it's not recommended. You should use json_encode
. If you have problems for transforming your object first, you can do it like this:
$obj = array(
"subscriptions" => array(
array("subscribe" => (string)$subscribe[0]),
array("subscribe" => (string)$subscribe[1]),
array("subscribe" => (string)$subscribe[2]),
array("subscribe" => (string)$subscribe[3]),
)
);
echo json_encode($obj);
Cheers
精彩评论