AJAX& JSON无法正常工作,没有错误或成功处理程序

时间:2012-11-07 11:42:08

标签: php ajax json magento

我有一些代码,我计划将其添加到Magento商店,一旦我在测试页面上工作,但不幸的是它不能在测试页面上工作。

Javascript如下:

function plusAddToCart(qty_textbox_id, prodID, highlight_div_id){
var qty = document.getElementById(qty_textbox_id).value;
qty = parseInt(qty) + 1;
document.getElementById(qty_textbox_id).value = qty;
 if(qty==0){
     $(highlight_div_id).style.backgroundColor = "#f7e9f4";
 }else{
     $(highlight_div_id).style.backgroundColor = "#ebcde5";
 }

 $.ajax({                                      
  url: "addtocart.php",
  data: "prodID="+prodID,
  type: "POST",
  dataType: 'json',
  success: function(data) {
    alert("DONE");
  }
});
}
</script>

<div style="width:70px; margin:9px auto 0 auto;">
   <input type='button' name='plus' onclick='plusAddToCart("qty1", "693", "product_highlight_693");' id="plus" class="cart-plus-minus" value='+'/>
   <input name="qty" type="text" id="qty0" readonly="readonly" maxlength="5" value="0" class="quantity-box" />
</div>

PHP:

 header("Content-Type: text/html");

 require_once 'app/Mage.php'; 
 Mage::app("default"); 
 Mage::getSingleton("core/session", array("name" => "frontend")); 
 $session = Mage::getSingleton("customer/session"); 

 $userData=Mage::helper('customer')->getCustomer()->getData(); 
 $cart = Mage::getSingleton('checkout/cart'); 
 $yourProId = $_POST['prodID']; 
 $qty=1; 
 $params = array( 'product' => $yourProId, 'related_product' => null, 'qty' => $qty );
 $product = new Mage_Catalog_Model_Product(); 
 $product->load($yourProId); 
 $cart->addProduct($product, $params); 
 $cart->save(); 
 Mage::getSingleton('checkout/session')->setCartWasUpdated(true); 
 $message = ('Your cart has been updated successfully.'); 
 Mage::getSingleton('checkout/session')->addSuccess($message);                    

任何人都可以看到为什么这不起作用的原因吗?

1 个答案:

答案 0 :(得分:4)

第一步是在AJAX调用中添加错误处理程序:

$.ajax({                                      
    url: "addtocart.php",
    data: "prodID="+prodID,
    type: "POST",
    dataType: 'json',
    success: function(data) {
        alert("DONE");
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert('Not done - ' + textStatus + ' ' + errorThrown);
    }
}

这可以让你更好地指出任何问题。

<强>更新

在您的具体情况下,我认为问题是:

的组合
  1. 将响应数据类型设置为“JSON”
  2. 网络服务不会返回任何内容
  3. 我认为请求可能会成功,但是当jQuery尝试解析JSON时,无法解析空响应。如果您将dataType更改为text,则可以避免此问题,因为它不会尝试任何解析。