我正在尝试向控制器发送多个选择的选项,但我不能
route
Route::post('/spacssendto/{id}', 'ProductController@spacssendto')->name('spacssendto');
ajax
$("body").on("click", ".sendspacsdatato", function(e){
e.preventDefault();
var id = $("#product_id").val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'subspecification_id': $('.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
controller
public function spacssendto(Request $request, $id) {
dd($request->all());
}
my form (output)
<form method="POST" action="http://sieffgsa.pp/admin/products/15" accept-charset="UTF-8">
<input name="_token" value="DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16" type="hidden">
<input name="product_id" id="product_id" value="15" type="hidden">
<div class="col-md-4">ram</div>
<div class="col-md-6">
<select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">
<option value="3">2gig</option>
<option value="4">4gig</option>
</select>
</div>
<div class="col-md-2">
<label for="">Actions</label><br>
<button type="button" id="sendspacsdatato" class=" sendspacsdatato btn btn-xs btn-success">Save</button>
</div>
</form>
PS:在我看来,这种表格是由Ajax印刷的,因此意味着 (涉及更多形式)这就是为什么我主要使用类 而不是ID。但是,当我点击“保存”按钮时,我将重复3次 网络(如果我有3种形式)
dd结果:
array:3 [ “ _token” =>“ DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16” “ product_id” =>“ 15” “ subspecification_id” => null ]
感谢Seva Kalashnikov
修复了该问题,仅是为了帮助他人,我将在此处发布最终结果,以便您可以使用完整的代码,希望对您有所帮助。
javascript
$(document).ready(function() {
$("body").on("click", ".sendspacsdatato", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': $(this).closest('form').find('select.subspecifications').val()
},
success: function (data) {
alert('Specifications added successfully.').fadeIn().delay(6000).fadeOut();
},
error: function (data) {
console.log('Error!');
}
});
});
});
controller
public function spacssendto(Request $request) {
$this->validate($request, array(
'product_id' => 'required',
'subspecifications' => 'required',
));
$product = Product::find($request->product_id);
$product->subspecifications()->sync($request->subspecifications, false);
}
答案 0 :(得分:0)
您需要在同一select
元素内获得{s}类为subspecifications
的{{1}}
form
尝试以下代码:
'subspecification_id': $(this).closest('form').find('select.subspecifications').val()