【发布时间】:2018-08-06 17:25:11
【问题描述】:
我已经创建了 ajax 函数来调用控制器,并且在控制器中我已经获取了一些数据并以 json 的形式返回,但是在 ajax 函数中作为响应它正在打印整个 html 页面,而不仅仅是 json 数据。
控制器:
<?php
class Mage_Catalog_ProductwidgetController extends Mage_Core_Controller_Front_Action
{
public function execute()
{
//$catid = $this->getCategory()->getId();
$_category = Mage::registry('current_category');
$catid = $_category->getId();
$_productCollection = Mage::getModel('catalog/category')->load($catid)
->getProductCollection()
->addAttributeToSelect('*')
->addFieldToFilter('status', 1)
->addAttributeToFilter('visibility', 4)
->joinField('is_in_stock',
'cataloginventory/stock_item',
'is_in_stock',
'product_id=entity_id',
'is_in_stock=1',
'{{table}}.stock_id=1',
'left');
foreach ($_productCollection as $_product) {
$_product->getData();
$json_products[] = array(
'name' => $_product->getName(),
'url' => $_product->getProductUrl(),
'entity_id' => $_product->getEntityId());
}
$this->getResponse()->clearHeaders()->setHeader('Content-type', 'application/json', true);
$this->getResponse()->setBody(json_encode($json_products));
}
}
阿贾克斯:
jQuery.ajax({
type: 'POST',
url: "<?php echo $this->getUrl('/controller/'); ?>",
success : function(data){
console.log(data);
}
});
我错了,它返回页面html而不是json数据。
【问题讨论】:
-
在 Ajax 调用中使用 dataType: "json"。
参考:stackoverflow.com/questions/17426199/…
标签: php json ajax magento magento-1.9