【问题标题】:Call controller by ajax but returning html instead of just json data in magento 1.9通过 ajax 调用控制器,但在 magento 1.9 中返回 html 而不仅仅是 json 数据
【发布时间】: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数据。

【问题讨论】:

标签: php json ajax magento magento-1.9


【解决方案1】:

只需打印您想要返回的 JSON 和 die()。该调用仅生成原始输出,因此没有理由通过视图运行它。

【讨论】:

    【解决方案2】:

    代替

    $this->getResponse()->clearHeaders()->setHeader('Content-type', 'application/json', true);
     $this->getResponse()->setBody(json_encode($json_products));
    

    使用$this-&gt;getResponse()-&gt;setBody(Zend_Json::encode($json_products));返回json输出。

    【讨论】:

      【解决方案3】:

      首先你必须在你的ajax参数中添加dataType : 'json',你的ajax代码将是

      jQuery.ajax({
                  type: 'POST',
                  url: "<?php echo $this->getUrl('/controller/'); ?>",
                  dataType : 'json',
                  success : function(data){
                     console.log(data);
                  }
              });
      

      然后在您的控制器中设置您的响应如下

      $this->getResponse()->setHeader('Content-type', 'application/json');
      $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($json_products));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-19
        • 1970-01-01
        • 2016-11-24
        • 2014-10-24
        • 2013-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多