lea*_*eed 9 ajax routes laravel
如何将此ajax调用中的id传递给TestController getAjax()函数?当我进行调用时,url是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>
Run Code Online (Sandbox Code Playgroud)
TestController.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;
}
Run Code Online (Sandbox Code Playgroud)
lea*_*eed 14
最后,我只是将参数添加到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>
Run Code Online (Sandbox Code Playgroud)
TestController.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;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
你的ajax的方法是GET,但在控制器中你使用$ _POST来获取值.这是个问题.
你可以
$id = $_GET['id'];
Run Code Online (Sandbox Code Playgroud)
但是在Laravel中,它有一个很好的方法来做到这一点.就在这里.您无需担心用于请求的HTTP谓词,因为所有谓词都以相同的方式访问输入.
$id = Input::get("id");
Run Code Online (Sandbox Code Playgroud)
如果需要,可以过滤请求类型以控制异常.文档在这里
确定请求是否使用AJAX
if (Request::ajax())
{
//
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
41866 次 |
最近记录: |