我试图从一个似乎总是空的AJAX帖子中获取一个值。我已经尝试在发布帖子之前打印该值并且它工作正常但我无法通过$ this-> input-> post()
获取值HTML
<?php if ($product_info->stock > '1'){?>
<button class="btn btn-lg btn-primary" product_id = "<?php echo $product_info->id;?>" id = "addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
的Javascript
$(document).ready(function(){
$("#addtocart").click(function(){
var productid = $(this).attr('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: productid,
cache: true,
success: function(productid){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(productid){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
}
});
});
});
控制器
$productcart = array();
if($this->session->userdata('cartsession')){
$cartsession = $this->session->userdata('cartsession');
foreach($cartsession as $id=>$val){
$productcart[$id] = $val;
}
}
$productcart[$this->input->post('productid')] = 50; -->sample value
$this->session->set_userdata('cartsession', $productcart);
$cartsession = $this->session->userdata('cartsession');
答案 0 :(得分:1)
数据参数具有certian格式,可使用ajax将值发送到服务器。
试试这个......
$(document).ready(function(){
$("#addtocart").click(function(){
var productid = $(this).attr('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: {productid : productid},
cache: true,
success: function(productid){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(productid){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Opps! </strong>Something went wrong.</div>')
}
});
});
});
答案 1 :(得分:0)
使用HTML5的数据属性&#39; data-product_id&#39;而是拥有自己的属性&#39; product-id&#39;,因此HTML代码如下所示:
<button class="btn btn-lg btn-primary" data-product_id="<?php echo $product_info->id;?>" id="addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
此外,如果您有多个“添加到购物车”,请为元素指定类名称。用于分组的按钮,如下所示:
<button class="btn btn-lg btn-primary" data-product_id="<?php echo $product_info->id;?>" class="addtocart"><i class="fa fa-shopping-cart"></i>Add to Cart</button><?php}?>
现在是时候使用jQuery来使用data属性了:
var product_id = $(this).data('product_id');
现在,整个代码看起来像
$(document).ready(function(){
$(".addtocart").click(function(){
var product_id = $(this).data('product_id');
$.ajax({
type: "POST",
url: "<?php echo base_url();?>shoppingcart",
data: product_id,
cache: true,
success: function(response){
$("#cartstatus").html('<div class="alert alert-success"><strong>Success! </strong>Item has been added to the cart.</div>');
}, error: function(response){
$("#cartstatus").html('<div class="alert alert-danger"><strong>Oops! </strong>Something went wrong.</div>')
}
});
});
});
希望它有效。