ajaxReturn是php內(nèi)置方法嗎
ajaxReturn不是php內(nèi)置方法,ajaxReturn是ThinkPHP中的Action類提供了ajaxReturn方法,用于AJAX調(diào)用后返回?cái)?shù)據(jù)給客戶端,并且支持JSON、XML和EVAL三種方式給客戶端接受數(shù)據(jù),通過配置DEFAULT_AJAX_RETURN進(jìn)行設(shè)置,默認(rèn)配置采用JSON格式返回?cái)?shù)據(jù),在選擇不同的AJAX類庫(kù)的時(shí)候可以使用不同的方式返回?cái)?shù)據(jù)。
ajaxReturn使用
要使用ThinkPHP的ajaxReturn方法返回?cái)?shù)據(jù)的話,需要遵守一定的返回?cái)?shù)據(jù)的格式規(guī)范。ThinkPHP返回的數(shù)據(jù)格式包括:
status 操作狀態(tài)
info 提示信息
data 返回?cái)?shù)據(jù)
$this->ajaxReturn(返回?cái)?shù)據(jù),提示信息,操作狀態(tài));
返回?cái)?shù)據(jù)data可以支持字符串、數(shù)字和數(shù)組、對(duì)象,返回客戶端的時(shí)候根據(jù)不同的返回格式進(jìn)行編碼后傳輸。如果是JSON格式,會(huì)自動(dòng)編碼成JSON字符串,如果是XML方式,會(huì)自動(dòng)編碼成XML字符串,如果是EVAL方式的話,只會(huì)輸出字符串data數(shù)據(jù),并且忽略status和info信息。
下面是一個(gè)簡(jiǎn)單的例子:
$User=M("User");//實(shí)例化User對(duì)象 $result = $User->add($data); if ($result){ //成功后返回客戶端新增的用戶ID,并返回提示信息和操作狀態(tài) $this->ajaxReturn($result,"新增成功!",1); }else{ //錯(cuò)誤后返回錯(cuò)誤的操作狀態(tài)和提示信息 $this->ajaxReturn(0,"新增錯(cuò)誤!",0); }
$data['status'] = 1; $data['info'] = 'info'; $data['size'] = 9; $data['url'] = $url; $this->ajaxReturn($data,'JSON');
ajaxReturn源碼
/** * Ajax方式返回?cái)?shù)據(jù)到客戶端 * @access protected * @param mixed $data 要返回的數(shù)據(jù) * @param String $type AJAX返回?cái)?shù)據(jù)格式 * @return void */ protected function ajaxReturn($data,$type='') { if(func_num_args()>2) {// 兼容3.0之前用法 $args = func_get_args(); array_shift($args); $info = array(); $info['data'] = $data; $info['info'] = array_shift($args); $info['status'] = array_shift($args); $data = $info; $type = $args?array_shift($args):''; } if(empty($type)) $type = C('DEFAULT_AJAX_RETURN'); if(strtoupper($type)=='JSON') { // 返回JSON數(shù)據(jù)格式到客戶端 包含狀態(tài)信息 header('Content-Type:text/html; charset=utf-8'); exit(json_encode($data)); }elseif(strtoupper($type)=='XML'){ // 返回xml格式數(shù)據(jù) header('Content-Type:text/xml; charset=utf-8'); exit(xml_encode($data)); }elseif(strtoupper($type)=='EVAL'){ // 返回可執(zhí)行的js腳本 header('Content-Type:text/html; charset=utf-8'); exit($data); }else{ // TODO 增加其它格式 } }