php返回json数组
1.后端
//处理json数组中文问题 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数组 function JSON($array) { arrayRecursive($array, 'urlencode', true); $json = json_encode($array); return urldecode($json); }
//调用 $data = array(); $data['success']="false"; $data['message']="用户名不存在,请重新输入"; echo JSON($data);
2.前端
$.post("ajax.php?mod=member&code=check_user_exist",{username:username},function(data){ var json=$.parseJSON(data); if(json.success){ alert(json.success); }else{ alert(json.success); } });