The new features of ThinkPHP 3.1 improve the support for Ajax

  • 2021-07-02 23:39:01
  • OfStack

ThinkPHP version 3.1 provides more complete support for AJAX, as shown in:

1. Judge the improvement of AJAX mode

Now you can directly use the constant IS_AJAX to determine whether it is requested by AJAX mode, which is used to replace the isAjax method of Action class before. The advantage is that you can judge in any code. The error and success methods of Action class have built-in support for AJAX automatic judgment.

2. Improvement of ajaxReturn method

The original ajaxReturn method can only return data with fixed structure, including data, status and info index information. If additional data information needs to be extended, it can only be returned through ajaxAssign method, while ThinkPHP version 3.1 improves ajaxReturn method itself, which can better support ajax data expansion, for example:


$data['status'] = 1;
$data['info'] = ' Return information ';
$data['data'] = ' Return data ';
$data['url'] = 'URL Address ';
$this->ajaxReturn($data);

data value arrays can be defined at will.
The improved ajaxReturn method is also compatible with the previous writing, such as:


$this->ajaxReturn($data,'info',1);

The system will automatically incorporate info and 1 parameters into the $data array, which is equivalent to assignment


$data['info'] = 'info';
$data['status'] = 1;
$data['data'] = $data;
$this->ajaxReturn($data);

But this usage is no longer recommended.

3. success and error methods improve support for ajax

Under ajax mode, success and error methods of Action class are improved, and the parameters of these two methods will be converted into info, status and url parameters of data data of ajaxReturn method. You can also support passing in other parameters, and there are two ways to support ajax value passing. Take the success method as an example. The first method is to pass ajax data directly


$data['code'] = 200;
$data['name'] = 'ThinkPHP';
$this->success(' Success prompt information ',' Jump address ',$data);

Or adopt


$this->assign('code',200);
$this->assign('name','thinkphp');
$this->success(' Success prompt information ',' Jump address ');

The final ajax data information returned to the client is an array of name, code, info, status, and url.


Related articles: