think\Request.php 参照isAjax函数编写isFetch函数
/**
* 当前是否fetch请求
* @access public
* @param bool $fetch true 获取原始fetch请求
* @return boolean
*/
public function isFetch($fetch = false)
{
$value = $this->server('HTTP_REQUEST_TYPE', '', 'strtolower');
$result = ('fetch' === $value) ? true : false;
if (true === $fetch) {
return $result;
} else {
return $this->param(Config::get('var_fetch')) ? true : $result;
}
}think\App.php line 135 修改自动识别响应输出类型 // 默认自动识别响应输出类型
$isAjax = $request->isAjax();
$isFetch = $request->isFetch();
if ($isAjax) {
$type = Config::get('default_ajax_return');
} elseif ($isFetch) {
$type = Config::get('default_fetch_return');
} else {
$type = Config::get('default_return_type');
}
$response = Response::create($data, $type);traits\controller\Jump.php 重写getResponseType函数/**
* 获取当前的response 输出类型
* @access protected
* @return string
*/
protected function getResponseType()
{
$isAjax = Request::instance()->isAjax();
$isFetch = Request::instance()->isFetch();
if ($isAjax) {
return Config::get('default_ajax_return');
} elseif ($isFetch) {
return Config::get('default_fetch_return');
} else {
return Config::get('default_return_type');
}
}配置文件中添加两项// 表单fetch伪装变量
'var_fetch' => '_fetch',
// 默认fetch 数据返回格式,可选json xml ...
'default_fetch_return' => 'json',前端代码fetch("url", {
method: 'POST',
headers: {
"Request-Type": "fetch", // 必须
},
credentials: 'same-origin',
body: formData
})
.then(function(response) {
// TODO
})
.then(function(data) {
// TODO
})
.catch(function(error) {
// TODO
}); 最佳答案