简体   繁体   English

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

[英]unable to retrieve data sent via ajax in controller Laravel 5.1

I am sending data via ajax to my controller as 我通过ajax将数据发送到我的控制器

$.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'));
}*/
});

and in the controller I am using 在我正在使用的控制器中

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

I am getting nothing in $id . 我在$id得不到任何东西。 I have also tried $_POST['id'] which says undefined index id . 我也尝试过$_POST['id'] ,它表示undefined index id How I can retrive the id value? 我怎样才能检索id值? $request->has('id') returns false too. $request->has('id')返回false。

You should use the Request class instead of Input : 您应该使用Request类而不是Input

public function getUserMessages(\Illuminate\Http\Request $request){

        $id = $request->id;
        $messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();

        return $messages;
    }

Your ajax call doesn't work and will throw a 500 Server Error because you need to pass laravel's csrf token with it whenever you POST something. 您的ajax调用不起作用并将抛出500服务器错误,因为每当您发布一些内容时,您需要使用laravel的csrf令牌。 Create a meta tag at the top of your blade view like: 在您的刀片视图顶部创建一个元标记,如:

<meta name="_token_" content="{{ csrf_token() }}">

and get the value when you are doing the ajax call: 并在执行ajax调用时获取值:

$.ajax({
    url: '/test',
    type: 'POST',
    data: { 
        id: sessionStorage.getItem('user_id'),
        _token:document.getElementsByName('_token_')[0].getAttribute('content') 
    },
    success:function(id){
    alert(id);
}
});

Most likely the success function in your ajax call will only alert [object Object], to get a better overview over whats returned, use 很可能你的ajax调用中的成功函数只会提醒[object Object],以便更好地了解返回的内容,使用

console.log(id);

instead. 代替。

You may also create an error function for the ajax call so that possible errors will be shown. 您还可以为ajax调用创建一个错误函数,以便显示可能的错误。 Just do add 只需添加

error: function(err){
    console.log(err);
}

after the success function. 成功后的功能。

The problem is that you are setting the application content as json, You don't need to set the content. 问题是您将应用程序内容设置为json,您不需要设置内容。

jQuery ajax jQuery ajax

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8') contentType(默认值:'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
    }
});

Hope this help. 希望这有帮助。 Your ajax should work now. 你的ajax现在应该工作了。

Have you a route for AJAX requests? 你有AJAX请求的路线吗? (I don't see it.) (我没看到。)

Please try following code: 请尝试以下代码:

In your AJAX code: 在您的AJAX代码中:

$.ajax({
    type: "POST",
    url: "{{ route('ajax_route') }}",
    data: { _token:  "{{ csrf_token() }}", data: "sample data" },
    success: function(data){
        $(".result").html(data);
    },
    dataType: "json"
});

In your controller code: 在您的控制器代码中:

public function ajaxAction(Request $request){
  if ($request->isXmlHttpRequest() && $request->isMethod('post')) {
    $data = $request->input('data', null);
    echo json_encode($data);
  }
}

In your route code: 在您的路线代码中:

Route::post('/ajax_route', ['as' => 'ajax-action', 'uses' => 'YourController@ajaxAction']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM