我有一个AJAX调用,如下所示:
function getPosts(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post("get-posts",
function(data, status){
console.log(data);
console.log(status);
});
}在我的routes/web.php,里,我有:
Route::post('get-posts','PagesController@getPosts');controller_function看起来是这样的:
public function getPosts(){
$posts = DB::table('users_queries')->get();
echo json_encode($posts);
}但问题是控制台记录了一个空字符串。为了确保我正在转换一个php对象,我还调用了gettype($posts);函数并返回了对象。然后,我认为问题可能在<script>标记中,并尝试了这个typeof(data)和返回的字符串,这确保了数据是字符串。但是当我运行console.log(data.length);时,我感到震惊,因为它记录了0。但我能做的事情有:
public function getPosts(){
$posts = DB::table('users_queries')->where('id', 1)->first();
echo $posts->author;
}一切都很美好,但我无法得到所有的东西。那么,我的代码有什么问题呢?我想不出来。请帮帮忙。
发布于 2018-05-11 14:07:27
以JSON形式返回您的响应:https://laravel.com/docs/5.6/responses#json-responses
public function getPosts(){
$posts = DB::table('users_queries')->get();
return response()->json([
'status' => 'success',
'data' => $posts
]);
}https://stackoverflow.com/questions/50294144
复制相似问题