使用Ajax控制器Laravel传递数据 [英] Laravel passing data using ajax to controller
本文介绍了使用Ajax控制器Laravel传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何通过ID从这个AJAX调用的TestController getAjax()函数?当我做呼叫的网址是testUrl?ID = 1
路线::得到('testUrl','@的TestController getAjax');
<脚本>
$(函数(){
$('#键)。点击(函数(){
$阿贾克斯({
网址:testUrl,
键入:GET,
数据:{编号:1},
成功:函数(响应)
{
$('#的东西)HTML(响应);
}
});
});
});
< / SCRIPT>
TestController.php
公共职能getAjax()
{
的$ id = $ _ POST ['身份证'];
$测试=新TestModel();
$结果= $测试 - >的getData($ ID);
的foreach($结果为$行)
{
$的HTML =
'&其中; TR>
< TD> 。 $行向>的名字。 '< / TD> 。
'&其中; TD>' 。 $行向>地址。 '< / TD> 。
'&其中; TD>' 。 $行向>年龄。 '< / TD> 。
'< / TR>';
}
返回$ HTML;
}
解决方案
在最后,我刚添加的参数的路线::得到()和阿贾克斯URL调用了。我改变$ _ POST ['身份证']到$ _GET ['身份证']在getAjax()函数,这得到了我的回应回
路线::得到('testUrl / {ID}','@的TestController getAjax');
<脚本>
$(函数(){
$('#键)。点击(函数(){
$阿贾克斯({
网址:testUrl / {ID},
键入:GET,
数据:{编号:1},
成功:函数(响应)
{
$('#的东西)HTML(响应);
}
});
});
});
< / SCRIPT>
TestController.php
公共职能getAjax()
{
的$ id = $ _GET ['身份证'];
$测试=新TestModel();
$结果= $测试 - >的getData($ ID);
的foreach($结果为$行)
{
$的HTML =
'&其中; TR>
< TD> 。 $行向>的名字。 '< / TD> 。
'&其中; TD>' 。 $行向>地址。 '< / TD> 。
'&其中; TD>' 。 $行向>年龄。 '< / TD> 。
'< / TR>';
}
返回$ HTML;
}
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
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
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;
}
解决方案
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('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
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;
}
这篇关于使用Ajax控制器Laravel传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文