Laravel Ajax 调用控制器中的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26015256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:09:22  来源:igfitidea点击:

Laravel Ajax Call to a function in controller

phplaravellaravel-4

提问by Yunus Aslam

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.

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

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

我的控制器位于 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";
    }
}

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

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

回答by DavidT

In your routes.phpfile add

在您的routes.php文件中添加

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

Then use your ajax call to send data to /orderdatathe data will be passed through to your OrderDatamethod in the DashBoardController

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

So your ajax call would become

所以你的ajax调用会变成

$.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')