本教程是一款php ajax返回 json数据实例,就是利用ajax实时的接受json.php文件发送的数据请求,并且进行了处理,代码如下:
- <!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()
- {
-
- try
- {
-
- xmlhttp=new xmlhttprequest();
- }
- catch (e)
- {
-
- 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 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--;
- }
-
-
-
-
-
-
-
-
-
- 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"}
- ?>
|