小编典典

Laravel使用Ajax将数据传递给控制器

ajax

如何将ID从此Ajax调用传递给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;
}

阅读 523

收藏
2020-07-26

共1个答案

小编典典

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