无法在控制器 Laravel 5.1 中检索通过 ajax 发送的数据

2021-12-18 00:00:00 php javascript ajax laravel-5.1 controller

我通过ajax向我的控制器发送数据

I am sending data via ajax to my controller as

$.ajax({
    url: 'test',
    type: 'POST',
    data: { id: sessionStorage.getItem('user_id') },
    dataType: 'json',
    contentType: "application/json; charset=utf-8"/*,
    success:function(id){
    alert(sessionStorage.getItem('user_id'));
}*/
});

在我使用的控制器中

public function getUserMessages(){

        $id = Input::get('id');
        $messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
        echo "id is ",$id;
        return $messages;
    }

我在 $id 中什么也没得到.我也试过 $_POST['id'] 表示 undefined index id.我如何检索 id 值?$request->has('id') 也返回 false.

I am getting nothing in $id. I have also tried $_POST['id'] which says undefined index id. How I can retrive the id value? $request->has('id') returns false too.

推荐答案

问题是你设置的应用内容为json,不需要设置内容.

The problem is that you are setting the application content as json, You don't need to set the content.

jQuery ajax

contentType(默认:'application/x-www-form-urlencoded; charset=UTF-8')

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

$.ajax({
    url: 'test',
    type: 'POST',
    data: { id: sessionStorage.getItem('user_id') },
    dataType: 'json',

    success:function(data){
         console.log(data); // always good to output content for debugginn
    }
});

希望对您有所帮助.你的 ajax 现在应该可以工作了.

Hope this help. Your ajax should work now.

相关文章