Magento 2 Controller中的获取代码片段讲解
首先我们要知道Magento 2中Controller里面的request请求工作原理,下面我简单的介绍下Magento 2主要使用的先是Magento\Framework\HTTP\PhpEnvironment\Request.php类的方法,即使Magetno 2集成的框架php环境,再次依次获取Zend 2 中php环境类Zend\Http\PhpEnvironment\Request.php、和最底层的 Zend\Http\Request.php类,下面我们将详细介绍。
A. PHP代码判断是否Ajax?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $credentials = null; $httpBadRequestCode = 400; $response = null; $resultRaw = $this->resultRawFactory->create(); try { $credentials = [ 'username' => $this->getRequest()->getPost('username'), 'password' => $this->getRequest()->getPost('password') ]; } catch (\Exception $e) { return $resultRaw->setHttpResponseCode($httpBadRequestCode); } if (!$credentials || $this->getRequest()->getMethod() !== 'POST' || !$this->getRequest()->isXmlHttpRequest()) { //如何不是ajax,不是post的提交方式直接返回 return $resultRaw->setHttpResponseCode($httpBadRequestCode); } |
B.下面是判断Magento 2 URL请求的方式POST
1 | $this->getRequest()->getMethod() !== 'POST' |
C.下面是判断Magento 2 URL请求的方式GET
1 | $this->getRequest()->getMethod() !== 'GET' |
D.下面是判断Magento 2 URL请求是否AJAX
1 2 3 4 | if ( !$this->getRequest()->isXmlHttpRequest() ) { //如何不是ajax //写入你要写的代码 } |
E.或者使用下面切记,使用下面的如果GET方式请求参数为带有ajax的key,则返回会时真的。
1 | $this->getRequest()->isAjax() |
F.Magento 2的前端的ajax代码,ajax-login.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | define([ "jquery", "Magento_Ui/js/modal/alert", "mage/translate", "Magento_Ui/js/modal/modal", "jquery/ui" ], function ($, alert, $t,modal) { "use strict"; $.widget('post.ajaxLogin', { options: { ajaxLoginUrl: '', ajaxRegisterUrl: '', isLoggedIn:'', logingEle:'#send2-login', login:'#customer-popup-login', register:'#customer-popup-register', addToCartButton: '#product-addtocart-button', formLogin:'#customer-popup-login-form', fromRegister:'#customer-popup-form-register', registerpopuplogin:'#customer-popup-sign-in', authentication_options:{ type: 'popup', responsive: true, innerScroll: true, title: '', buttons: false, modalClass : 'customer-popup' } }, _create: function () { var self = this; if(!self.options.isLoggedIn){ // add to cat $(self.element).click(function (e) { e.preventDefault(); if (self.element.length) { //add custom self.options.authentication_options.title = self.options.popupLoginTitle; modal(self.options.authentication_options, self.options.login); self._setStyleCss(self.options.innerWidth); $(self.options.login).modal('openModal'); self._ajaxLoginSubmit(); } }); //register $(self.options.customerPopupRegistration).click(function(e){ e.preventDefault(); e.stopPropagation(); $(self.options.login).modal('closeModal'); self.options.authentication_options.title = self.options.popupRegisterTitle; modal(self.options.authentication_options, self.options.register); self._setStyleCss(600); $(self.options.register).modal('openModal'); self._ajaxRegisterSubmit(); }); //register login $(self.options.registerpopuplogin).click(function (e) { e.preventDefault(); $(self.options.register).modal('closeModal'); //add custom self.options.authentication_options.title = self.options.popupLoginTitle; modal(self.options.authentication_options, self.options.login); self._setStyleCss(self.options.innerWidth); $(self.options.login).modal('openModal'); self._ajaxLoginSubmit(); }); } }, _setStyleCss: function(width) { width = width || 400; if (window.innerWidth > 786) { $(this.options.formLogin+','+this.options.fromRegister).parents('.modal-inner-wrap').css({'max-width': width+'px'}); } }, _ajaxRegisterSubmit:function(){ var self = this, form = $(this.options.fromRegister), inputElement = form.find('input'); inputElement.keyup(function (e) { form.find('#register-ajax-error-cart').hide(); form.find('.messages').html(''); }); form.submit(function (e) { e.stopPropagation(); e.preventDefault(); if (form.validation('isValid')) { $.ajax({ url: self.options.ajaxRegisterUrl, data: form.serialize(), type: 'POST', dataType: 'json', showLoader: true, success: function (result) { if(result.errors) { form.find('.messages').html(result.message); form.find('#register-ajax-error-cart').show(); } else { $(self.options.register).modal('closeModal'); location.reload(); } } }); } return false; }); }, _ajaxLoginSubmit: function () { var self = this, form = $(this.options.formLogin), inputElement = form.find('input'),addToCartButton = $(this.options.addToCartButton); inputElement.keyup(function (e) { form.find('#login-ajax-error-cart').hide(); form.find('.messages').html(''); }); form.submit(function (e) { e.stopPropagation(); e.preventDefault(); if (form.validation('isValid')) { $.ajax({ url: self.options.ajaxLoginUrl, data: form.serialize(), type: 'POST', dataType: 'json', showLoader: true, success: function (result) { if(result.errors) { form.find('.messages').html(result.message); form.find('#login-ajax-error-cart').show(); } else { $(self.options.login).modal('closeModal'); location.reload(); } } }); } return false; }); } }); return $.post.ajaxLogin; }); |
G.Magento 2后端的代码返回值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | protected $resultJsonFactory; public function __construct( \Magento\Framework\App\Action\Context $context, \Magento\Customer\Model\Session $customerSession, \Magento\Framework\Json\Helper\Data $helper, \Magento\Framework\Data\Form\FormKey\Validator $formKeyValidator, AccountManagementInterface $customerAccountManagement, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory, \Magento\Framework\Controller\Result\RawFactory $resultRawFactory ) { parent::__construct($context); $this->customerSession = $customerSession; $this->helper = $helper; $this->formKeyValidator = $formKeyValidator; $this->customerAccountManagement = $customerAccountManagement; $this->resultJsonFactory = $resultJsonFactory; $this->resultRawFactory = $resultRawFactory; } /** @var \Magento\Framework\Controller\Result\Json $resultJson */ //使用的是上面的类,进行返回json对象的。 $resultJson = $this->resultJsonFactory->create(); return $resultJson->setData($response); |
H.获取Magento 2 URL cookie信息
1 | $this->getRequest()->getCookie($name) |
I.获取Magento 2 URL请求的参数信息,即使post和get参数都可以
1 | $this->getRequest()->getParams() |
J.获取Magento 2 URL请求方式controller方法
1 2 3 4 | $this->getRequest()->getOriginalPathInfo(); 例如:www.sky8g.com/en/sky8g/test/index?hello=sky8g 则输出为:/sky8g/test/index 注意不包含站点的store code即使不包含en |
K.获取Magento 2 URL请求方式post参数值方法
1 | $this->getRequest()->getPost($name) |
L.获取Magento 2 URL请求头部信息方法
1 | $this->getRequest()->getHeaders() |
M.获取Magento 2 URL请求host域名,不带http://
1 | $this->getRequest()->getServer('SERVER_NAME') |
N.判断Magento 2 URL请求是否是安全请求方式
1 | $this->getRequest()->isSafeMethod() |