Magento 2正确的方式做ajax调用?

时间:2017-02-02 22:17:44

标签: php ajax magento2

这是我的控制者:

命名空间Mvp \ Mercury \ Controller \ Index;

class Display extends \Magento\Framework\App\Action\Action
{

protected $resultJsonFactory;

public function __construct(
    Context                                             $context,
    \Magento\Framework\Controller\Result\JsonFactory    $resultJsonFactory
) {

    $this->resultJsonFactory            = $resultJsonFactory;
    parent::__construct($context);
}


public function execute()
{
    $result                 = $this->resultJsonFactory->create();
    if ($this->getRequest()->isAjax())) 
    {
        $test=Array
        (
            'Firstname' => 'What is your firstname',
            'Email' => 'What is your emailId',
            'Lastname' => 'What is your lastname',
            'Country' => 'Your Country'
        );
        return $result->setData($test);
    }
}

}

我正在对这个控制器进行ajax调用,但是给了我错误,我正在尝试这种方式:

function addItemToShoppingCart(data)
{
console.log("You are about to add part: " + data.productNumber + " with qty: " + data.quantity + " and price: " + data.price);

var sku        = data.productNumber,
   qty        = data.quantity,
   price      = data.price,
   base_url   = '<?php echo $this->getUrl(); ?>',
   module_url = 'helloworld/index/display',
   full_url   = base_url + module_url;

var cart_info = {
    sku : sku,
    qty : qty,
    price: price
};

console.log(full_url);
console.log(cart_info);

$.ajax({
    showLoader: true,
    url: full_url,
    data: cart_info,
    type: "POST",
    dataType: 'json'
}).done(function (data) {

    console.log('success');

});
} 

基于我不知道为什么它给我错误,它给出的确切代码是500,我检查了权限,他们拥有一切,所以这可能是什么问题?

1 个答案:

答案 0 :(得分:0)

由于许可,

500错误没有发生。如果问题是获得许可,那么它将显示403错误。代码有一些错误时会出现500错误。尝试通过运行以下命令来检查错误日志或设置部署模式:developer:

php bin/magento deploy:mode:set developer

现在,您将能够看到确切的错误。现在您可以解决它,或者如果您遇到问题,请在此处粘贴错误。