AJAX in TP returns ajaxReturn()

The system supports any AJAX class library, and the Action class provides the ajaxReturn method for returning data to the client after an AJAX call. And supports JSON, XML and EVAL three ways to accept data to the client, set by configuring DEFAULT_AJAX_RETURN, the default configuration returns data in JSON format, you can use different methods to return data when selecting different AJAX class libraries.
If you want to use the ajaxReturn method of ThinkPHP to return data, you need to comply with certain format specifications for the returned data. The data formats returned by ThinkPHP include:

status Operational status
info prompt information   
data return data
$this->ajaxReturn(return data, prompt information, operation status);

The returned data data can support strings, numbers, arrays, and objects. When returning to the client, it is encoded and transmitted according to different return formats. If it is in JSON format, it will be automatically encoded into a JSON string. If it is in XML format, it will be automatically encoded into an XML string. If it is in EVAL format, only string data data will be output, and status and info information will be ignored.

Here is a simple example:

copy code
$User=M("User"); // Instantiate the User object
 $result = $User->add( $data ); if ( $result ){ // After success, return the user ID added by the client and return Prompt information and operation status $this->ajaxReturn( $result,"Added successfully!",1 ); } else { // Return the wrong operation status and prompt information after an error $this->ajaxReturn(0,"Added Error!",0 ); }
copy code
$data['status'] = 1;
$data['info'] = 'info'; $data['size'] = 9; $data['url'] = $url; $this->ajaxReturn($data,'JSON');

 thinkphp source code:

copy code
/**
     * Ajax way to return data to the client
     * @access protected
     * @param mixed $data The data to return
     * @param String $type AJAX return data format
     * @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' ) { // Return JSON data format to client including status information header('Content-Type:text/html; charset=utf -8' ); exit(json_encode( $data )); } elseif( strtoupper( $type)=='XML' ){ // return xml format data header('Content-Type:text/xml; charset=utf- 8' ); exit(xml_encode( $data )); } elseif( strtoupper( $type)=='EVAL' ){ // return executable js script header('Content-Type:text/html; charset=utf -8' ); exit( $data );}else { // TODO add other formats } }
copy code

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324933019&siteId=291194637