天天看点

php ajax返回 json数据实例

<!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>无标题文档</title>

<script type="text/javascript" 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?";

        xmlHttp.onreadystatechange = handleStateChange;

        xmlHttp.open("POST", url, true);//xmlHttp.open("GET", url, true);

        xmlHttp.send("cid="+id); //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" οnclick="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'=>$_GET['cid']

       );

echo JSON($array);

?>