Laravel passing data using ajax to controller

2019-02-03 15:07发布

问题:

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

回答1:

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


回答2:

Your ajax's method is GET but in controller you use $_POST to get value. This is problem.

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.

$id = Input::get("id");

If you want, you can filter request type to control exception. Docs here

Determine If The Request Is Using AJAX

if (Request::ajax())
{
    //
}