【发布时间】:2018-04-13 12:26:17
【问题描述】:
问题
如何使用复选框使用 Ajax 更新我的表的 only 1 column?
说明
我想使用复选框并更新我的active 列,值将是1 或0。如果检查值为1,否则为0。
代码
html
<label class="switch">
<input type="checkbox" data-name="active" data-id="{{ $courier->id }}">
<span class="slider round"></span>
</label>
data-name 是我的专栏名称
data-id 是我的行号
controller function
public function Updatecourierstatus(Request $request) {
try {
$id = $request->input('id');
$field = $request->input('name');
$courier = Courier::findOrFail($id);
$courier->{$field} = //must get 1 or 0 here;
$courier->save();
} catch (Exception $e) {
return response($e->getMessage(), 400);
}
return response('', 200);
}
route
Route::post('/Updatecourierstatus', 'CourierController@Updatecourierstatus')->name('Updatecourierstatus');
});
JavaScript
不知道如何处理这部分!
更新
我的最新代码:
script
<script>
$(function (){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('label.switch input[type="checkbox"]').on('click', function (event) {
$.post("{{route('Updatecourierstatus')}}", {
id: $(this).data("id"),
name: $(this).data("name"),
state: $(this).is(":checked") ? 0 : 1 // toggles
}).done(function(data) {
console.log(data)
});
});
});
</script>
controller
public function Updatecourierstatus(Request $request) {
try {
$id = $request->input('id');
$field = $request->input('name');
$state = $request->input('state');
$courier = Courier::findOrFail($id);
$courier->{$field} = (int) $state;
$courier->save();
} catch (Exception $e) {
return response($e->getMessage(), 400);
}
return response('', 200);
}
html
<label class="switch">
<input class="status" type="checkbox" data-name="active" data-id="{{ $courier->id }}" {{ $courier->active == '1' ? 'checked' : ''}}>
<span class="slider round"></span>
</label>
问题
- 我的开关按钮没有按预期工作,为价值
1和关闭 对于值0,始终关闭。 - 我添加了
{{ $courier->active == '1' ? 'checked' : ''}},以便 根据数据库中的值正确打开和关闭,但从那时起我的值 不会在 DB 中改变,它们会保持当前值并且不会得到 更新了
已修复
问题是 state: $(this).is(":checked") ? 0 : 1 作为“What are the PHP operators “?” and “:” called and what do they do?”解释我必须使用 state: $(this).is(":checked") ? 1 : 0
【问题讨论】:
标签: javascript php ajax laravel