我正在尝试使用“jquery”ajax 从 laravel Controller 获取数据。但是,我遇到了parsererror
。根据 laravel 文档,如果我们使用 response()->json(data)
,它会自动设置 header Content-Type= 'application/json'
,并且我也尝试在ajax端设置相同的 header ,但没有区别。我也尝试过
contentType:'application/json',
dataType: "json",
accept:'application/json',
但它们都不起作用。这是我的代码设置:
app.js
var initlides = function () {
return $.ajax({
url: _url,
contentType:'application/json',
dataType: "json",
accept:'application/json',
success: function (data) {
console.log(data)
},
error: function (textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
});
};
controller.php
public function index()
{
echo $section;
$carousels= array();
$carousel = Carousel::where('section_name', 'intro')->get();
return response()->json($carousel);
}
我搜索了其他类似的问题,但没有一个有帮助。请帮忙。
最佳答案
response()->json()仅接受数组,这就是您收到错误的原因,您必须使用 Collection::toArray
方法才能将集合转换为数组:
$carousel = Carousel::where('section_name', 'intro')->get()->toArray();
return response()->json($carousel);
或者只需这样做:
$carousel = Carousel::where('section_name', 'intro')->get();
return $carousel->toArray();
关于javascript - 'jquery' 'aja' x 从 laravel Controller 获取数据时引发解析器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48026128/