且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel Ajax 调用控制器中的函数

更新时间:2023-01-24 10:30:47

在你的 routes.php 文件中添加

Route::post('/orderdata', 'DashBoardController@OrderData');

然后使用您的 ajax 调用将数据发送到 /orderdata 数据将传递到 DashBoardController 中的 OrderData 方法p>

所以你的 ajax 调用会变成

$.ajax({类型:POST",url: '/orderdata',//这是我更新的数据:{ id:7 }}).done(函数(味精){警报(味精);});

如果你想访问数据,你需要像这样将它添加到你的方法中

class DashBoardController 扩展 BaseController {公共函数 DashView(){返回视图::make('dashboard');}public function OrderData($postData){//这是我想从 ajax 调用的函数//用那个帖子数据做一些很棒的事情返回我在";}}

并更新您的路线

Route::post('/orderdata/{postdata}', 'DashBoardController@OrderData')

I am new to laravel and I want to make an ajax call to a function written in controller. I have done the following but not working.

In View :

$.ajax({
    type: "POST",
    url: 'OrderData', // Not sure what to add as URL here
    data: { id: 7 }
}).done(function( msg ) {
    alert( msg );
});

My Controller which is located inside app/controllers/DashBoardController.php and inside DashBoardController.php I have

class DashBoardController extends BaseController {
    public function DashView(){
        return View::make('dashboard');
    }

    public function OrderData(){ // This is the function which I want to call from ajax
        return "I am in";
    }
}

My Question is how can I make an ajax call from view on page load to a function inside my DashBoardController.php ?? Thanks.

In your routes.php file add

Route::post('/orderdata', 'DashBoardController@OrderData');

Then use your ajax call to send data to /orderdata the data will be passed through to your OrderData method in the DashBoardController

So your ajax call would become

$.ajax({
    type: "POST",
    url: '/orderdata', // This is what I have updated
    data: { id: 7 }
}).done(function( msg ) {
    alert( msg );
});

If you want to access the data you will need to add that into your method like so

class DashBoardController extends BaseController {
    public function DashView(){
        return View::make('dashboard');
    }

    public function OrderData($postData){ // This is the function which I want to call from ajax
        //do something awesome with that post data 
        return "I am in";
    }
}

And update your route to

Route::post('/orderdata/{postdata}', 'DashBoardController@OrderData')