【问题标题】:How to send data attribute to laravel controller (to store on database) using ajax?如何使用ajax将数据属性发送到laravel控制器(存储在数据库中)?
【发布时间】:2019-09-13 15:50:34
【问题描述】:

我是 Laravel 的初学者,我创建了这段代码用于练习将图像中的订单号更改存储到数据库中。但我将值存储在 属性 中。这里的案例是设置图像的顺序编号,使用“可排序”函数 jQuery。

我在互联网上进行了一些搜索,但大多数情况下他们使用<input type="hidden" name="someName" value="{{ here's the value }}" 来存储新订单号的值。我只是好奇是否有可能从属性中获取数据。

这是我的代码:

HTML:

<table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>No.</th>
                                    <th>Image</th>
                                    <th>Status</th>
                                    <th>Order Number</th>
                                </tr>
                            </thead>
                            {{ csrf_field() }}
                            <tbody class='sort-list'>
                                <?php $i=1; ?>

                                @foreach ($images as $image)

                                <tr class="dataArray" data-index="{{ $image->id }}" data-position="{{ $image->order_number }}">
                                    <input type="hidden"
                                    <th scope="row">
                                        <?php echo $i; ?>.
                                    </th>
                                    <td>
                                        <div class="col-lg-3" style="margin-bottom: 0;">
                                            <a href="{{ asset('cms/images/carousel/'.$image->url_img)}}" data-sub-html="Description">
                                                <img class="img-responsive thumbnail" style="margin-bottom: 0;" src="{{ asset('cms/images/carousel/'.$image->url_thumb)}}">
                                            </a>
                                        </div>
                                    </td>
                                    <td>
                                        @if ($image->is_active == 1)
                                        <span class="label bg-green">Active</span>
                                        @else
                                        <span class="label bg-deep-orange">Inactive</span>
                                        @endif
                                    </td>
                                    <td>
                                        {{ $image->order_number }}
                                    </td>
                                </tr>
                                <?php $i++; ?>
                                @endforeach
                            </tbody>
                        </table>

所以我使用 data-index 和 data-position 属性存储到数据库中。

这是我的 jQuery 和 Ajax:

<script>
    $('.sort-list').sortable({
        axis: 'y',
        opacity: 0.7,
        cursor: 'pointer',
        update: function (event, ui) {
            $(this).children().each(function (index) {
                if ($(this).attr('data-position') != (index+1)) {
                    $(this).attr('data-position', (index+1)).addClass('updated');
                }
            });

            saveNewPositions();
        }
    });
    function saveNewPositions() {
        var positions = [];
        $('.updated').each(function () {
            positions.push([$(this).attr('data-index'), $(this).attr('data-position')]);
            $(this).removeClass('updated');
        });

        $.ajax({
            url: "{{ route('/admin/setCarouselOrder') }}",
            method: 'GET',
            dataType: 'text',
            data: {
                update: 1,
                positions: positions
            }, success: function (response) {
                console.log(response);
            }
        });
    }

如果这是 PHP Native,我将使用以下代码:

if (isset($_POST['update'])) {
        foreach($_POST['positions'] as $position) {
           $index = $position[0];
           $newPosition = $position[1];

           $conn->query("UPDATE country SET position = '$newPosition' WHERE id='$index'");
        }

        exit('success');
    }

我在控制器上的试用是这样的:

public function setCarouselOrder(Request $r) {
   $result = Carousel::find($r->id);

   $newNumber = $r->data-position;
   foreach($result as $data)
   {
       $data->order_number=$newNumber;
   }
}

为了您的信息,我正在使用“模型”来访问我的名为“Carousel”的数据库。 我在 laravel 上的路线是:

Route::get('/admin/setCarouselOrder', 'AdminController@setCarouselOrder')-&gt;name('/admin/setCarouselOrder')

但是我对如何在 laravel 控制器上实现这一点有点困惑?请帮我找出方法。在这里需要一个解决方案。

非常感谢

【问题讨论】:

  • 您在服务器端使用$_POST 方法,在ajax 中使用GET,所以在ajax 中更改并将method: 'GET', 替换为method: 'POST',
  • 这只是示例,自上次试用以来我还没有更改。我用于“PHP native”的方法是POST。但是我在 laravel 上通过 json 编辑数据的另一个试验是使用 GET 方法,它可以工作。让我知道它是怎么回事.. 谢谢
  • 我已经从我在控制器上所做的添加,它只是不工作。我已经阅读了 laravel 文档,但我仍然对申请我的案子感到困惑。谢谢@SandeepSudhakaran,感激不尽
  • 请检查我的答案。

标签: php jquery ajax laravel


【解决方案1】:

在控制器中使用以下函数,

注意:请不要忘记添加use Illuminate\Http\Request;

 public function setCarouselOrder(Request $request){
    foreach($request->positions as $position) {
       $index = $position[0];
       $newPosition = $position[1];
       $affectedRows = Country::whereId($index)->update(['position' => $newPosition]);
    }
} 

并且您的路线想要(使用 POST 提交表单 Web 服务)

Route::post('/admin/setCarouselOrder', 'AdminController@setCarouselOrder')->name('admin.setCarouselOrder')

假设您有一个Country.php 模型文件 希望这有帮助。如果您需要更多说明,请在评论中告诉我

【讨论】:

  • 完美运行,非常感谢。所以我一直在寻找的答案是 --> first attribute = $position[0] (无论我改变名字,总是这样)。其次是 $position[1] 等等.. 对吗?
  • 哦,顺便说一句,如果我仍然使用GET 方法,我想知道这是否会成为未来的错误。因为我忘记改了,但它仍然可以正常工作..
  • 能否请您出示$request-&gt;all()。那么我可以尝试提出更好的选择。现在我不知道您的请求 Formdata 是什么样的
  • 不推荐按索引取值。您可以发送 key:value 对。 $index 是否对所有职位都相同?
  • $index = 每个图像的 ID。使用print_r($request-&gt;all()); exit; 结果是Array ( ).. 好奇怪
猜你喜欢
  • 2017-03-11
  • 2021-03-25
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 2017-04-29
  • 2019-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多