我想使用AJAX发布一个表单,因为我创建了一个表单,当我在控制器中放入这两行代码时工作正常:
$ this-> Security-> config(' unlockedFields',[' product_id']);
$这 - >安全 - >配置(' unlockedActions',阵列('更新'));
如果删除此代码我
错误:控制台中的错误请求。
<?php echo $this->Form->create('Cart',array('id' => 'saveForm'));
$total=0;
foreach ($products as $product):
echo $product['product_name'];
echo $this->Form->input('product_id.',array('value'=>$product['product_id'],'type' => 'number'));
echo $this->Form->input('count.',array('type'=>'number', 'label'=>false,
'class'=>'form-control input-sm', 'value'=>$product['count']));
echo $product['count']*$product['product_price'];
endforeach;
echo $total;
echo $this->Form->submit('Save');
echo $this->Form->end();
?>
控制器操作:
public function update() {
$this->autoRender = false;
if (!empty($this->request->data)) {
$cart = array();
foreach ($this->request->data['count'] as $index=>$count) {
if ($count>0) {
$productId = $this->request->data['product_id'][$index];
$cart[$productId] = $count;
}
}
$this->Carts->saveProduct($cart);
$carts = $this->Carts->readProduct();
$products = array();
if (null!=$carts) {
foreach ($carts as $productId => $count) {
$product = $this->Products->get($productId);
$product['count'] = $count;
$products[]=$product;
}
}
$this->set('products', $products);
$this->render('cart_view');
$this->set(compact('products'));
}
}
index.ctp
$(document).on("submit", "#saveForm", function(ev) {
var formData = $('#saveForm').serialize();
var formUrl ="http://localhost/multi_shopping/Singles/update";
$.ajax({
type: 'POST',
url: formUrl,
data: formData,
dataType: 'html',
async : false,
success: function(data,textStatus,xhr){
$('#PPMiniCart').html('');
$('#PPMiniCart').html(data);
$('#PPMiniCart').show();
},
error: function(xhr,textStatus,error){
alert("error"+error);
}
});
ev.preventDefault();
return false;
});