<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"/> <title>JSON - TEST</title> <script type="text/javascript" src="/js/prototype.js"></script> <script language="JavaScript" type="text/javascript">...<!-- function chat () ...{ // try { var url ='server.php'; new Ajax.Request(url, ...{ method: 'post', asynchronous: true, onLoading : function()...{}, onSuccess: function(transport, json) ...{ // Remainder of the code alert(json.name+' : '+json.desc+' : '+json.attach) } }); // } catch (e) {} } function chat2 () ...{ // try { var url ='server.php?ret=1'; new Ajax.Request(url, ...{ method: 'post', asynchronous: true, onLoading : function()...{}, onSuccess: function(req) ...{ // Remainder of the code var json = parseJSON(req); alert(json.name+' : '+json.desc+' : '+json.attach) } }); // } catch (e) {} } function parseJSON (request) ...{ try...{ return eval('('+ request.responseText +')'); }catch (e) ...{} } --></script> </head> <body> <a href="#" onclick="chat();">Get Chat By Prototype</a><br/> <a href="#" onclick="chat2();">Get Chat By Self</a> <div id="chatbox"></div> </body> </html>
server.php :
<?php include_once('JSON.php'); // create a new instance of Services_JSON $json=new Services_JSON(); // convert a complexe value to JSON notation, and send it to the browser $value=array('name'=>'stone','desc'=>iconv('gb2312','utf-8','哈哈'),'attach'=>array(1,2,'baz')); $output=$json->encode($value); if (isset($_REQUEST['ret'])) { // header('Content-type: text/x-json; charset=utf-8'); echo$output; // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] } else { header('X-JSON: ('.$output.')'); } // accept incoming POST data, assumed to be in JSON notation $input=file_get_contents('php://input',1000000); $value=$json->decode($input); ?>