【发布时间】: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')->name('/admin/setCarouselOrder')
但是我对如何在 laravel 控制器上实现这一点有点困惑?请帮我找出方法。在这里需要一个解决方案。
非常感谢
【问题讨论】:
-
您在服务器端使用
$_POST方法,在ajax 中使用GET,所以在ajax 中更改并将method: 'GET',替换为method: 'POST', -
这只是示例,自上次试用以来我还没有更改。我用于“PHP native”的方法是
POST。但是我在 laravel 上通过 json 编辑数据的另一个试验是使用GET方法,它可以工作。让我知道它是怎么回事.. 谢谢 -
我已经从我在控制器上所做的添加,它只是不工作。我已经阅读了 laravel 文档,但我仍然对申请我的案子感到困惑。谢谢@SandeepSudhakaran,感激不尽
-
请检查我的答案。