我遇到了将动态字段添加到数据库中的问题,如果我返回所有值,则会输入值,但是如果我尝试添加到数据库中,则会出现500错误。 这是我的动态领域:
var i = 1;
$('#add_field').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td class="col-md-5"><textarea class="name borders table-control" type="text" rows="1" cols="45" name="name[]"></textarea></td><td class="col-md-2"><input class="borders table-control price" type="text" name="price[]"></td><td class="col-md-2"><input class="borders table-control qty" type="text" name="qty[]"></td><td class="col-md-2"><input class="form-control total" type="text" name="total[]"></td><td class="text-center"><span id="'+i+'" style="color: red" name="remove" class="btn_remove"><i class="fa fa-times" aria-hidden="true"></i></span></td></tr>');
});
这是我的Ajax电话:
$(document).on('change','.qty',function(){
var id = $("#inv_id").val();
var tr = $(this).closest('tr');
var name = tr.find(".name").val();
var price = tr.find(".price").val();
var qty = tr.find(".qty").val();
var total = tr.find(".total").val();
$.ajax({
type: "POST",
url: '/product',
data: {'id': id, 'name': name, 'price': price, 'qty': qty, 'total': total, '_token':$('input[name=_token]').val()},
success: function( data ) {
console.log(data);
},
error: function(data){
alert("fail");
}
});
});
这是我的控制器:
public function product(Request $request){
$products = $request->all();
$id = $products['id'];
$name = $products['name'];
$price = $products['price'];
$qty = $products['qty'];
$total = $products['total'];
for( $i = 0; $i < count($name); $i++) {
$prod = new Product();
$prod->invoice_id = $id;
$prod->name = $name[$i];
$prod->price = $price[$i];
$prod->qty = $qty[$i];
$prod->total = $total[$i];
$prod->save();
}
return response()->json($prod->toArray(), 200);
}
这是我的产品型号
protected $fillable = [ 'invoice_id', 'name', 'qty', 'price', 'total' ];
我尝试过Product :: create($ request-&gt; all),实际上我已经尝试了所有我知道的东西。这就是为什么我需要你帮助的人。
答案 0 :(得分:0)
所有我不得不这样做是刷新页面。
public function product(Request $request){
$prod = new Product();
$prod->invoice_id = $request->id;
$prod->name = $request->name;
$prod->price = $request->price;
$prod->qty = $request->qty;
$prod->total = $request->total;
$prod->save();
return response()->json($prod->toArray(), 200);
}
$(document).on('change','.qty',function(){
var name = [];
var price = [];
var qty = [];
var total = [];
var id = $("#inv_id").val();
var tr = $(this).closest('tr');
name = tr.find(".name").val();
price = tr.find(".price").val();
qty = tr.find(".qty").val();
total = tr.find(".total").val();
$.ajax({
type: "POST",
url: '/product',
data: {id: id, name: name, price: price, qty: qty, total: total, '_token':$('meta[name="csrf-token"]').attr('content')},
success: function( data ) {
$('#form').load(location.href + ' #form');
location.reload();
}
});
});