Laravel Ajax 调用控制器中的函数
我是 laravel 的新手,我想对用控制器编写的函数进行 ajax 调用.我做了以下但没有工作.
在视图中:
$.ajax({类型:POST",url: 'OrderData',//不确定在此处添加什么作为 URL数据:{ id:7 }}).done(函数(味精){警报(味精);});
我的控制器位于 app/controllers/DashBoardController.php在 DashBoardController.php 里面我有
class DashBoardController 扩展 BaseController {公共函数 DashView(){返回视图::make('dashboard');}public function OrderData(){//这是我想从 ajax 调用的函数返回我在";}}
我的问题是如何从页面加载视图到我的 DashBoardController.php 中的函数进行 ajax 调用?谢谢.
解决方案在你的 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')
相关文章