如果我尝试使用 return response()->json($categorie);
返回一个 JSON 字符串,我得到一个空响应。
如果我将 return
替换为 echo
,那么我会得到
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json {"id":5,"name":"blah","parent":4,"visible":"yes""position":0,"created_at":"2016-06-29 15:23:25","updated_at":"2016-06-29 15:23:25"}
作为浏览器输出。
我正在使用 Laravel 5.2。 完整代码如下:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Categories;
class ApiController extends Controller
{
public static function categorieGetById($id) {
$categorie = Categories::find($id);
echo response()->json($categorie);
// return response()->json($categorie);
}
}
更新: Controller 不返回任何内容。每个 return
都会产生一个空输出。
为什么?
最佳答案
你应该使用 toJson()方法。
$categorie = Categories::find($id)->toJson();
echo $categorie; // your json output
return $categorie; // same json output
The toJson method converts the collection into JSON.
在您当前的代码中,
$categorie = Categories::find($id);
return response()->json($categorie); // your json output with return
注意:- 你必须在这里写return
。
在上面的代码中,如果你写echo,
echo response()->json($categorie);
然后会显示
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json {"id":5,"name":"blah","parent":4,"visible":"yes","position":0,"created_at":"2016-06-29 15:23:25","updated_at":"2016-06-29 15:23:25"}
关于php - Laravel 5.2 不返回任何响应作为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38121459/