doucheng4660 2018-05-11 14:03
浏览 87

无法从laravel中的AJAX调用获取responseText

I have an AJAX call that looks like this:

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);
        });
}

And in my routes/web.php, I have:

Route::post('get-posts','PagesController@getPosts');

And the controller_function looks like this:

public function getPosts(){
        $posts = DB::table('users_queries')->get();
        echo json_encode($posts);
    }

But the problem is that the console logs an empty string. To assure that I was converting a php object, I called the gettype($posts); function as well and it returned object. Then I thought the problem might be in the <script> tags and tried this typeof(data) and that returned string as well which made sure that the data was string. But when I ran console.log(data.length);, I was shocked because it logged 0. But I was able to do things like:

public function getPosts(){
    $posts = DB::table('users_queries')->where('id', 1)->first();
    echo $posts->author;
}

And everything ran sweet, but I am unable to get the whole json. So what is the problem in my code? I am unable to figure it out. Please help.

  • 写回答

1条回答 默认 最新

  • douxiaqin2062 2018-05-11 14:07
    关注

    Return your response as 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
        ]);
    }
    
    评论

报告相同问题?