Laravel 使用 ajax 将数据传递给控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26351085/
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
Laravel passing data using ajax to controller
提问by learntosucceed
How do I pass the id from this ajax call to the TestController getAjax() function? When I do the call the url is testUrl?id=1
如何将此 ajax 调用中的 id 传递给 TestController getAjax() 函数?当我打电话时,网址是 testUrl?id=1
Route::get('testUrl', 'TestController@getAjax');
<script>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl',
type: 'GET',
data: { id: 1 },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
测试控制器.php
public function getAjax()
{
$id = $_POST['id'];
$test = new TestModel();
$result = $test->getData($id);
foreach($result as $row)
{
$html =
'<tr>
<td>' . $row->name . '</td>' .
'<td>' . $row->address . '</td>' .
'<td>' . $row->age . '</td>' .
'</tr>';
}
return $html;
}
回答by learntosucceed
In the end, I just added the parameter to the Route::get() and in the ajax url call too. I changed $_POST['id'] to $_GET['id'] in the getAjax() function and this got my response back
最后,我只是将参数添加到 Route::get() 和 ajax url 调用中。我在 getAjax() 函数中将 $_POST['id'] 更改为 $_GET['id'] ,这得到了我的回复
Route::get('testUrl/{id}', 'TestController@getAjax');
<script>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl/{id}',
type: 'GET',
data: { id: 1 },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
测试控制器.php
public function getAjax()
{
$id = $_GET['id'];
$test = new TestModel();
$result = $test->getData($id);
foreach($result as $row)
{
$html =
'<tr>
<td>' . $row->name . '</td>' .
'<td>' . $row->address . '</td>' .
'<td>' . $row->age . '</td>' .
'</tr>';
}
return $html;
}
回答by Tam Nguyen
Your ajax's method is GET but in controller you use $_POST to get value. This is problem.
您的 ajax 方法是 GET 但在控制器中您使用 $_POST 来获取值。这是问题。
You can you
你可以吗
$id = $_GET['id'];
But in Laravel, it have a pretty method to do this. It's here. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs.
但是在 Laravel 中,它有一个很好的方法来做到这一点。它在这里。您无需担心用于请求的 HTTP 动词,因为所有动词都以相同的方式访问输入。
$id = Input::get("id");
If you want, you can filter request type to control exception. Docs here
如果需要,您可以过滤请求类型以控制异常。文档在这里
Determine If The Request Is Using AJAX
确定请求是否使用 AJAX
if (Request::ajax())
{
//
}
回答by Abhishek Sharma
#in your controller function
public function getAjax()
{
#check if request is ajax
if ($request->ajax()) {
//your code
}
return $your_data;
}

