加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:08:15 所属栏目:百科 来源:网络整理
导读:如何将此ajax调用中的id传递给TestController getAjax()函数?当我进行调用时,url是testUrl?id = 1 Route::get('testUrl','TestController@getAjax');script $(function(){ $('#button').click(function() { $.ajax({ url: 'testUrl',type: 'GET',data: { i
如何将此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>

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读