Laravel Ajax对控制器中的函数的调用


Laravel Ajax Call to a function in controller

我是laravel的新手,我想对控制器中编写的函数进行ajax调用。我做了以下工作,但没有工作。

视图中:

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

我的控制器,位于app/controllers/DashBoardController.php中在DashBoardController.php中,我有

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

我的问题是,如何从页面加载视图向DashBoardController.php中的函数进行ajax调用??谢谢

routes.php文件中添加

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

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

所以您的ajax调用将变成

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

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

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

并将您的路线更新到

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