| 代碼如下 |
複製代碼 |
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>php教程 ajax返回 網頁特效on資料執行個體</title> <script type="text/網頁特效" language="javascript"> var xmlhttp; function createxmlhttprequest() { //var xmlhttp=null; try { // firefox, opera 8.0+, safari xmlhttp=new xmlhttprequest(); } catch (e) { // internet explorer try { xmlhttp=new activexobject("msxml2.xmlhttp"); } catch (e) { xmlhttp=new activexobject("microsoft.xmlhttp"); } } return xmlhttp; } function startrequest(id) { createxmlhttprequest(); try { url="json.php?cid="+id; xmlhttp.onreadystatechange = handlestatechange; xmlhttp.open("post", url, true); xmlhttp.send(null); } catch(exception) { alert("xmlhttp fail"); } } function handlestatechange() { if(xmlhttp.readystate == 4) { if (xmlhttp.status == 200 || xmlhttp.status == 0) { var result = xmlhttp.responsetext; var json = eval("(" + result + ")"); alert('name:'+json.name); alert('age:'+json.age); alert('id:'+json.id); } } } </script> </head> <body> <div> <input type="button" value="ajaxtest" onclick="startrequest(5);" /> </div> </body> </html> |
json.php 檔案
| 代碼如下 |
複製代碼 |
<?php /************************************************************** * * 使用特定function對數組中所有元素做處理 * @param string &$array 要處理的字串 * @param string $function 要執行的函數 * @return boolean $apply_to_keys_also 是否也應用到key上 * @access public * *************************************************************/ function arrayrecursive(&$array, $function, $apply_to_keys_also = false) { static $recursive_counter = 0; if (++$recursive_counter > 1000) { die('possible deep recursion attack'); } foreach ($array as $key => $value) { if (is_array($value)) { arrayrecursive($array[$key], $function, $apply_to_keys_also); } else { $array[$key] = $function($value); } if ($apply_to_keys_also && is_string($key)) { $new_key = $function($key); if ($new_key != $key) { $array[$new_key] = $array[$key]; unset($array[$key]); } } } $recursive_counter--; } /************************************************************** * * 將數群組轉換為json字串(相容中文) * @param array $array 要轉換的數組 * @return string 轉換得到的json字串 * @access public * *************************************************************/ function json($array) { arrayrecursive($array, 'urlencode', true); $json = json_encode($array); return urldecode($json); } $array = array ( 'name'=>'希亞', 'age'=>20, 'id'=>$_post['cid'] );
|
echo json($array);
/*********
{"name":"希亞","age":"20"}
?>