我有关于在Ajax的第二个请求中插入最后一个插入ID的问题,当我查看列时所有插入的项都是0
值。所以现在我想插入每个具有自己唯一ID的表行
我有两张桌子:
wish_list_menu_order
wish_list_menu_belong_condiments
第一个插入是在wish_list_menu_order
上,所以在第一个插入的成功函数中,我有第二个请求,其中url是wish_list_menu_belong_condiments
。
第一次请求:
public function insert_wish_list_menu_order(Request $request)
{
$customer_id = $request->get('customer_id');
$append_customer_noun_order = $request->get('append_customer_noun_order');
$append_customer_noun_order_price = $request->get('append_customer_noun_order_price');
$now = new DateTime();
for ($count = 0; $count < count($append_customer_noun_order); $count++) {
DB::insert('INSERT INTO wish_list_menu_order (customer_id,wish_list_menu_name,wish_list_total_price,wish_created_at)
VALUES(?,?,?,?) ', [
$customer_id,
$append_customer_noun_order[$count],
$append_customer_noun_order_price[$count],
$now,
]);
}
}
第二个请求:
public function insert_wish_list_menu_belong_condiments(Request $request)
{
$Qty = $request->get('Qty');
$Item = $request->get('Item');
$Cost = $request->get('Cost');
$now = new DateTime();
$last_id_insert = DB::select('SELECT LAST_INSERT_ID() as id FROM wish_list_menu_order');
foreach ($last_id_insert as $result) {
$id_last_inserted = $result->id;
}
for ($count = 0; $count < count($Item); $count++) {
DB::insert('INSERT INTO wish_list_menu_belong_condiments (wish_menu_id,belong_condi_name,belong_condi_qty,belong_condi_price,belong_condi_created)
VALUES(?,?,?,?,?) ', [
$id_last_inserted,
$Item[$count],
$Qty[$count],
$Cost[$count],
$now,
]);
}
return response()->json('Successfully Inserted');
}
我的Ajax:
$('button#add_to_cart').on('click', function () {
var customer_id = $('#hidden_customer_id').val();
var parent_item = [];
var parent_amount = [];
//child
var child_item = [];
var child_quantity = [];
var child_amount = [];
//this is for parent item and amount
$('#noun_chaining_order').find('tr.condimentParent td.parent_item').each(function () {
parent_item.push($(this).text());
});
$('#noun_chaining_order').find('tr.condimentParent td.total').each(function () {
parent_amount.push($(this).text());
});
//end
//this is for child item,amount and quantity
$('#noun_chaining_order').find('tr.editCondiments td.child_item').each(function () {
child_item.push($(this).text())
});
$('#noun_chaining_order').find('tr.editCondiments td.total').each(function () {
child_amount.push($(this).text());
});
$('#noun_chaining_order').find('tr.editCondiments td.condiments_order_quantity').each(function () {
child_quantity.push($(this).text());
});
$.ajax({
url: '/insert_wish_list_menu_order',
type: 'post',
data: {
customer_id: customer_id,
append_customer_noun_order: parent_item,
append_customer_noun_order_price: parent_amount,
Qty: child_quantity,
Item: child_item,
Cost: child_amount
},
success: function (response) {
console.log(response);
$.ajax({
url: '/insert_wish_list_menu_belong_condiments',
type: 'post',
data: {
Qty: child_quantity,
Item: child_item,
Cost: child_amount
},
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
},
error: function (response) {
console.log(response);
}
});
});
这是我在表格中附加菜单项的方法。
$("tr#productClicked").click(function () {
var menu_name = $(this).closest("tr").find(".menu_name").text();
var menu_price = $(this).closest("tr").find(".menu_price").text();
var chain_id = $(this).closest("tr").find(".chain_id").text();
var menu_image = $(this).closest("tr").find(".menu_image").attr('src');
var menu_cat_id = $(this).closest("tr").find(".menu_id").text();
var customer_id = $('#hidden_customer_id').val();
if(chain_id == 0)
{
$("tbody#tbody_noun_chaining_order").
append("<tr class='condimentParent' style='background-color:'black !important',color:'white !important' '>\
<td></td><td class='parent_item'>"+menu_name+"</td><td class='total'>"+menu_price+"</td>\
<td><button class='removeorderWithOutCondi btn btn-danger form-control'>\
<i class='far fa-trash-alt'></i></button></td></tr>");
//computation of total click without chain
var sum_sub_total_price = 0;
$('td.total').each(function () {
sum_sub_total_price += parseFloat($(this).text());
});
var with_decimal_subprice = parseFloat(sum_sub_total_price).toFixed(2);
$('.append_customer_noun_order_price').text(with_decimal_subprice);
}
else
{
$("tbody#tbody_noun_chaining_order").
append("<tr class='condimentParent' style='background-color:'black !important',color:'white !important' '>\
<td></td><td class='parent_item'>"+menu_name+"</td><td class='total'>"+menu_price+"</td>\
<td><button class='removeorderWithOutCondi btn btn-danger form-control'>\
<i class='far fa-trash-alt'></i></button></td></tr>");
//after displaying the parent item get the condiments
$.ajax({
url:'/get_noun_group_combination',
type:'get',
data:{chain_id:chain_id},
success:function(response){
var noun_chaining = response[0].noun_chaining;
$.each(noun_chaining, function (index, el) {
var stringify_noun_chaining = jQuery.parseJSON(JSON.stringify(el));
var Qty = stringify_noun_chaining['Qty'];
var Condiments = stringify_noun_chaining['Condiments'];
var Price = stringify_noun_chaining['Price'];
var allow_to_open_condiments = stringify_noun_chaining['allow_to_open_condiments'];
var condiments_section_id = stringify_noun_chaining['condiments_section_id'];
$("tbody#tbody_noun_chaining_order").
append("<tr class='editCondiments'>\
<td class='condiments_order_quantity'>"+Qty+"</td>\
<td class='child_item'>*"+Condiments+"</td><td class='total'>"+Price+"</td>\
<td class='allow_to_open_condiments_conditional' style='display:none;'>"+allow_to_open_condiments+"</td>\
<td class='condi_section_id' style='display:none;'>"+condiments_section_id+"</td>\
</tr>");
});
}
});
}
});
$('button#add_to_cart').on('click',function () {
var customer_id = $('#hidden_customer_id').val();
var parent_item =[];
var parent_amount =[];
//child
var child_item =[];
var child_quantity =[];
var child_amount = [];
//this is for parent item and amount
$('#noun_chaining_order').find('tr.condimentParent td.parent_item').each(function(){
parent_item.push($(this).text());
});
$('#noun_chaining_order').find('tr.condimentParent td.total').each(function(){
parent_amount.push($(this).text());
});
//end
//this is for child item,amount and quantity
$('#noun_chaining_order').find('tr.editCondiments td.child_item').each(function(){
child_item.push($(this).text());
});
$('#noun_chaining_order').find('tr.editCondiments td.total').each(function(){
child_amount.push($(this).text());
});
$('#noun_chaining_order').find('tr.editCondiments td.condiments_order_quantity').each(function(){
child_quantity.push($(this).text());
});
$.ajax({
url: '/insert_wish_list_menu_order',
type: 'post',
data: {
customer_id: customer_id,
append_customer_noun_order: parent_item,
append_customer_noun_order_price: parent_amount,
Qty: child_quantity,
Item: child_item,
Cost: child_amount
},
success:function(response){
console.log(response);
$.ajax({
url: '/insert_wish_list_menu_belong_condiments',
type: 'post',
data: {
Qty: child_quantity,
Item: child_item,
Cost: child_amount
},
success:function(response){
console.log(response);
},
error:function(response) {
console.log(response);
}
});
},
error:function(response) {
console.log(response);
}
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<title></title>
</head>
<body>
<table class="table table-hover upsize_check" id="noun_chaining_order" style="border:none;">
<input type="hidden" name="" value="" id="hidden_customer_id">
<thead>
<tr style="font-size: 15px; color:white;">
<th scope="col">Qty</th>
<th scope="col">Items</th>
<th scope="col">Price</th>
<th>Action</th>
</tr>
</thead>
<tbody style="font-size:14px;" id="tbody_noun_chaining_order">
<tr class="condimentParent">
<td></td>
<td class="parent_item">$5.00 Extra Crispy 2 Piece Box</td>
<td class="total">5.00</td>
<td><button class="removeorderWithCondi btn btn-danger form-control">Delete</button></td>
</tr>
<tr class="editCondiments">
<td class="condiments_order_quantity">2</td>
<td class='child_item'>*Standard</td>
<td class="total">0.00</td>
<td class="allow_to_open_condiments_conditional" style="display:none;">Yes</td>
<td class="condi_section_id" style="display:none;">3</td>
</tr>
<tr class="editCondiments">
<td class="condiments_order_quantity">2</td>
<td class='child_item'>*Individual Fries</td>
<td class="total">0.00</td>
<td class="allow_to_open_condiments_conditional" style="display:none;">Yes</td>
<td class="condi_section_id" style="display:none;">2</td>
</tr>
<tr class="editCondiments">
<td class="condiments_order_quantity">1</td>
<td class='child_item'>*Buttery Bread</td>
<td class="total">0.00</td>
<td class="allow_to_open_condiments_conditional" style="display:none;">No</td>
<td class="condi_section_id" style="display:none;">4</td>
</tr>
<tr class="editCondiments">
<td class="condiments_order_quantity">1</td>
<td class='child_item'>*Chocolate Chip Cookie</td>
<td class="total">0.00</td>
<td class="allow_to_open_condiments_conditional" style="display:none;">No</td>
<td class="condi_section_id" style="display:none;">5</td>
</tr>
<tr class="editCondiments">
<td class="condiments_order_quantity">1</td>
<td class='child_item'>*355ml Pepsi</td>
<td class="total">0.00</td>
<td class="allow_to_open_condiments_conditional" style="display:none;">No</td>
<td class="condi_section_id" style="display:none;">6</td>
</tr>
<tr class="condimentParent" style="background-color:" black="" !important',color:'white="" !important'="" '=""> <td></td><td class="parent_item">BIG CRUNCH Sandwich</td><td class="total">7.29</td> <td><button class="removeorderWithOutCondi btn btn-danger form-control"> <i class="far fa-trash-alt"></i></button></td></tr>
</tbody>
</table>
<center>
<button type="button" class="btn btn-primary" style="background-color:#3D0081; border-color:#3D0081;" id="add_to_cart">Click to process the order</button>
</center>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
“生成的ID在每个连接的基础上在服务器中维护。”
在你的代码中,两个请求 - 第一个将父记录插入wish_list_menu_order
,第二个将子记录插入wish_list_menu_belong_condiments
可能在不同的MySQL连接上运行,不一定按顺序运行。不是在第二次调用时查询LAST_INSERT_ID()
,而是在将记录插入数据库并将其作为AJAX响应的一部分返回后调用它。
在您当前的代码中,所有记录将按顺序添加到wish_list_menu_order
,在此完成后,将添加子元素。在最好的情况下 - 只有在使用一个MySQL连接的情况下 - 您可能会获得父表的最后插入ID,并将此ID用于wish_list_menu_belong_condiments
中的所有插入。
wish_list_menu_order
的每个插入,执行一个AJAX调用并返回LAST_INSERT_ID()
。后端代码:
插入wish_list_menu_order
:
public function insert_wish_list_menu_order(Request $request)
{
$customer_id = $request->get('customer_id');
$append_customer_noun_order = $request->get('append_customer_noun_order');
$append_customer_noun_order_price = $request->get('append_customer_noun_order_price');
$now = new DateTime();
DB::insert('INSERT INTO wish_list_menu_order (customer_id,wish_list_menu_name,wish_list_total_price,wish_created_at)
VALUES(?,?,?,?) ', [
$customer_id,
$append_customer_noun_order,
$append_customer_noun_order_price,
$now,
]);
$last_id_insert = DB::select('SELECT LAST_INSERT_ID() as id FROM wish_list_menu_order');
return response()->json($last_id_insert);
}
插入wish_list_menu_belong_condiments
:
public function insert_wish_list_menu_belong_condiments(Request $request)
{
$Qty = $request->get('Qty');
$Item = $request->get('Item');
$Cost = $request->get('Cost');
$ParentId= $request->get('ParentId');
for ($count = 0; $count < count($Item); $count++) {
DB::insert('INSERT INTO wish_list_menu_belong_condiments (wish_menu_id,belong_condi_name,belong_condi_qty,belong_condi_price,belong_condi_created)
VALUES(?,?,?,?,?) ', [
$ParentId,
$Item[$count],
$Qty[$count],
$Cost[$count],
$now,
]);
}
return response()->json('Successfully Inserted');
}
前端代码:
// just for fiddle demo
var orderNumber = 358;
var customer_id = $('#hidden_customer_id').val();
$('#add_to_cart').on('click', function() {
// reset
var orders = [];
var menu;
$('#tbody_noun_chaining_order').children('tr').each(function() {
$row = $(this);
if ($row.hasClass('condimentParent')) {
// store a previous menu to the orders array if exists.
if (menu !== undefined) {
orders.push(menu);
}
menu = {
'total': $row.find('.total').text(),
'name': $row.find('.parent_item').text(),
'condiments': {
'Item': [],
'Qty': [],
'Total': []
}
};
} else if ($row.hasClass('editCondiments')) {
// row is a condiment, append elements to the previous "menu" variable
menu.condiments.Item.push($row.find('.child_item').text());
menu.condiments.Qty.push($row.find('.condiments_order_quantity').text());
menu.condiments.Total.push($row.find('.total').text());
}
});
if (menu) {
orders.push(menu);
}
storeOrder(orders);
});
function storeOrder(orders) {
for (var num in orders) {
// simulate storing the order
$.ajax('/echo/json', {
type: 'POST',
// as the call is asynchronous, make sure to provide all required reference data along with the call.
context: orders[num].condiments,
data: {
'json': '"' + (orderNumber++) + '"',
'customer_id': customer_id,
'append_customer_noun_order_price': orders[num].total,
'append_customer_noun_order': orders[num].name,
},
success: function(orderNumber) {
if (!isNaN(orderNumber)) {
$.ajax('/echo/json', {
context: orderNumber,
type: 'POST',
data: {
'ParentId': orderNumber,
'Item': this.Item,
'Qty': this.Qty,
'Total': this.Total,
'json': '{"condimentsCount": ' + this.Item.length + '}'
},
success: function(result) {
$('#result').append('Stored ' + result.condimentsCount + ' condiments for order ' +
this + '<br />');
}
}); // End of condiments save procedure
}
}
}); // End of menu save procedure
}
}
小提琴显示模拟的前端部分:
https://jsfiddle.net/Moonbird_IT/qbhnctre/
一般建议: