From bb9d7b2189d1e8c69a0fb07ef6eb98e828c39a77 Mon Sep 17 00:00:00 2001 From: Igor Wiedler Date: Tue, 3 Jan 2012 00:54:52 +0100 Subject: [PATCH] add some docs on using the lib with JSON, closes #3 --- README.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/README.md b/README.md index dc1cb85..6e0563b 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,38 @@ stream.addEventListener('bar', function (event) { }); ``` +### Sending JSON + +In most applications you will want to send more complex data as opposed to +simple strings. The recommended way of doing this is to use the JSON format. +It can encode and decode nested structures quite well. + +On the server side, simply use the `json_encode` function to encode a value: + +```php + array(21, 43, 127)); + +$stream + ->event() + ->setData(json_encode($data)); + ->end() + ->flush(); +``` + +On the client side, you can use `JSON.parse` to decode it. For old browsers, +where `JSON` is not available, see [json2.js](https://github.com/douglascrockford/JSON-js). + +```JavaScript +var stream = new EventSource('stream.php'); + +stream.addEventListener('message', function (event) { + var data = JSON.parse(event.data); + console.log('User IDs: '+data.userIds.join(', ')); +}); +``` + ### Custom handler By default the library will assume you are running in a traditional apache-like