所以我在使用Axios和VueJS时遇到了一些麻烦(我正在使用Quasar Framework)。我正在制作一个非常简单的电子商务网站。我在产品页面上有一个按钮,允许用户将该产品插入购物车。
<q-btn
@click="addToCart()"
>
Add to Cart
</q-btn>
当用户点击按钮时,我执行addToCart()
方法:
methods: {
addToCart () {
axios.post(this.getRootURL + 'app/actions/add_to_cart.php', {
product_id: this.$route.params.product_id,
quantity: this.quantity,
user_id: LocalStorage.get.item('user_id')
}).then(response => {
console.log("Product added...")
}).catch(e => {
console.log("Error... ")
}
}
}
然而,我遇到了一个问题。就像数据插入两次一样。第一行获取空user_id
,第二行获得正确的user_id
(See image)。
我确定我在使用VueJS或Axios时出错了,因为在使用Postman并直接向文件发送请求时,数据只会被正确插入一次。
有人可以帮忙吗?以前发生过这件事吗? :/
更新 这是我的服务器端PHP脚本。
add_to_cart.php
<?php
require '../Functions.php';
$obj = new User_Functions();
$addToCart = $obj->addToCart($_POST['product_id'], $_POST['quantity'], $_POST['user_id']);
if($addToCart){
echo 'true';
}else{
echo 'false';
}
?>
Functions.php
这是在User_Functions
类中执行的方法(我使用Medoo.in来管理对数据库的查询):
require 'init.php'; //Connection to my database
class User_Functions {
public function addToCart($product_id, $quantity, $user_id){
global $database;
$check_if_cart_active = $database->count("cart", [
"user_id" => $user_id
]);
//CHECK IF USER HAS AN ACTIVE CART
if($check_if_cart_active == 0){
// If user doesn't have an active cart add new cart and add the cart item
$database->insert("cart", [
"user_id" => $user_id,
"created_at" => time()
]);
$cart_id = $database->id();
$database->insert("cart_products", [
"cart_id" => $cart_id,
"product_id" => $product_id,
"quantity" => $quantity,
"created_at" => time()
]);
}else{
// Get cart_id of the active cart
$cart_id = $database->select("cart", [
"cart_id"
], [
"user_id" => $user_id
]);
$cart_id = $cart_id[0]['cart_id'];
//CHECK IF PRODUCT IS ALREADY IN CART
$check_if_product_in_cart = $database->count("cart_products",[
"AND" => [
"cart_id" => $cart_id,
"product_id" => $product_id
]
]);
//IF PRODUCT ISN'T IN CART ADD IT ELSE UPDATE THE QUANTITY
if($check_if_product_in_cart == 0){
$database->insert("cart_products", [
"cart_id" => $cart_id,
"product_id" => $product_id,
"quantity" => $quantity,
"created_at" => time()
]);
}else{
$database->update("cart_products", [
"quantity" => $quantity
], [
"AND" => [
"cart_id" => $cart_id,
"product_id" => $product_id
]
]);
}
}
return true;
}
}