php和ajax怎么调整,php和ajax的简单实现

步骤一、新建文件夹:js,把最新的jquery.js放里边。

步骤二、新建文件mygetjson.php,其内容为

class custom_json {

/**

* Convert array to javascript object/array

* @param array $array the array

* @return string

*/

public static function encode($array)

{

// determine type

if(is_numeric(key($array))) {

// indexed (list)

$output = '[';

for($i = 0, $last = (sizeof($array) - 1); isset($array[$i]); ++$i) {

if(is_array($array[$i])) $output .= self::encode($array[$i]);

else $output .= self::_val($array[$i]);

if($i !== $last) $output .= ',';

}

$output .= ']';

} else {

// associative (object)

$output = '{';

$last = sizeof($array) - 1;

$i = 0;

foreach($array as $key => $value) {

$output .= '"'.$key.'":';

if(is_array($value)) $output .= self::encode($value);

else $output .= self::_val($value);

if($i !== $last) $output .= ',';

++$i;

}

$output .= '}';

}

// return

return $output;

}

/**

* [INTERNAL] Format value

* @param mixed $val the value

* @return string

*/

private static function _val($val)

{

if(is_string($val)) return '"'.rawurlencode($val).'"';

elseif(is_int($val)) return sprintf('%d', $val);

elseif(is_float($val)) return sprintf('%F', $val);

elseif(is_bool($val)) return ($val ? 'true' : 'false');

else return 'null';

}

}

// prints: ** try it yourself, cannot post long lines here **

$big_test = array(

array(

'name' => array('John', 'Smith'),

'age' => 27,

'sex' => 0,

'height' => 180.53,

'is_human' => true,

'string' => 'Hello',

),

array(

'name' => array('Green', 'Alien'),

'age' => 642,

'sex' => null,

'height' => 92.21,

'is_human' => false,

'string' => 'こんにちは!', // test utf8 here

)

);

//echo custom_json::encode($big_test);//这个用于测试其是否返回的是json数据

echo $_GET['jsoncallback'].'('.custom_json::encode($big_test).')';//用一个回调返回

?>

步骤三、新建测试页面test.html,其内容为

Page Title

$(function(){

$('#btn').click(function(){

$.getJSON('json.php?jsoncallback=?',myfunction);

function myfunction(data)

{

var infoHtml = '';

$.each(data,function(contact,contactinfo)

{

// alert(contactinfo.name);

infoHtml+='

name:'+contactinfo.name+'

';

$('#info').html(infoHtml);

});

}

});

});

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值