我已经创建了一个本地存储项,我想使用AJAX将其发布到服务器。我遍历了localStorage项的数据,并将该数据推到新的数组中。现在,我想将该新数组发布到服务器,但是我在ajax调用中的数据字段返回0。
let shopItem = JSON.parse(localStorage.getItem('item'));
let array = [];
for (var i = 0; i < shopItem.length; i++){
let chosen_date = shopItem[i].chosen_date;
let product_id = shopItem[i].product_id;
let quantity = shopItem[i].quantity;
array.push({product_id: product_id, quantity: quantity, chosen_date: chosen_date});
}
$.ajax({
url: ajaxscript.ajax_url,
method: "post",
data: {
action: "add_this_shit_to_cart",
product_id: array.product_id, // LOOP HERE THROUGH ARRAY??
chosen_date: array.chosen_date, // LOOP HERE THROUGH ARRAY??
quantity: array.quantity // LOOP HERE THROUGH ARRAY??
},
success: function(response) {
console.log("resp: ", response);
},
error: function(err) {
console.log(err);
}
});
那么,我是否必须为每个字段再次遍历数组?
在我的functions.php中,我有这个:
function add_this_shit_to_cart() {
ob_start();
$product_id = intval($_POST['product_id'] );
$chosen_date = intval($_POST['chosen_date'] );
$quantity = intval($_POST['quantity'] );
$data = array(
'product' => $product_id,
'chosen_date' => $chosen_date,
'quantity' => $quantity
);
echo json_encode($data);
die();
}
add_action( 'wp_ajax_add_this_shit_to_cart', 'add_this_shit_to_cart' );
add_action( 'wp_ajax_nopriv_add_this_shit_to_cart', 'add_this_shit_to_cart' );
有人可以帮我吗?
是的,基本的问题是:此数据是否存储在数据库中?
我不是wordpress的新手,所以...
答案 0 :(得分:0)
我无法发表评论,因此我将其发布为答案。
您是否尝试过console.log(shopItem)?据我了解,shopItem是一个对象。您无法像在此处那样遍历对象:
for (var i = 0; i < shopItem.length; i++){
let chosen_date = shopItem[i].chosen_date;
let product_id = shopItem[i].product_id;
let quantity = shopItem[i].quantity;
array.push({product_id: product_id, quantity: quantity, chosen_date: chosen_date});
}
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of