gpt4 book ai didi

ajax - Laravel 使用 ajax 将数据传递给 Controller

转载 作者:行者123 更新时间:2023-12-02 20:12:30 25 4
gpt4 key购买 nike

如何将此 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

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;
}

最佳答案

最后,我只是将参数添加到 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

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 使用 ajax 将数据传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26351085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com