#json #ajax #controller #magento2
#json #ajax #контроллер #magento2
Вопрос:
С моего контроллера я возвращаю данные JSON в свой вызов Ajax, но они всегда попадают в раздел ошибок, даже если это не ошибка.
jQuery.ajax({
type: 'POST',
url: '/yxcustomer/index/emailpreferences',
data: {"category1": category1,"category2":category2 , "category3":category3,"category4":category4,"category5":category5,"category6":category6,"category7":category7,
"latest1":latest1,"latest2":latest2,"latest3":latest3,"latest4":latest4,
"frequency":frequency,
"email":email,"firstName":firstName , "lastName":lastName},
dataType: "json",
success: function (data) {
console.log("data response success prefe " JSON.stringify(data));
},
error: function (error) {
console.log("data response error prefe " JSON.stringify(error));
}
});
Controller code
protected $resultJsonFactory;
public function __construct(
MagentoFrameworkControllerResultJsonFactory $resultJsonFactory,
MagentoFrameworkAppActionContext $context
) {
$this->resultJsonFactory = $resultJsonFactory;
parent::__construct($context);
}
public function execute()
{
try{
return $this->resultJsonFactory->create()->setData(['success' => true,'contact'=>json_encode($contact) ,'message' => $this->messageManager->addSuccessMessage("Successfully updated email preferences")]);
} catch (Exception $e) {
return $this->resultJsonFactory->create()->setData(['success' => false,'message' => $this->messageManager->addErrorMessage('Email preferences cannot be updated')]);
}
}
Все еще этот код успеха
$this->resultJsonFactory->create()->setData(['success' => true,'contact'=>json_encode($contact) ,'message' => $this->messageManager->addSuccessMessage("Successfully updated email preferences")])
Всегда переходит в часть с ошибкой ajax
error: function (error) {}
ответ в Ajax является
ошибка ответа на данные prefe {«readyState»:4,»responseText»: «чтение контактов с equalto filtern{«success»:true,»contact»:»{«id»:»c74668c8-e886-4592-8950-273a7a6ab72d»,»email»:»an@gmail.com»,»status»:»onboarding»,»msgPref»:»html»,»source»:»api»,»customSource»:»source»,»created»:»2019-03-20T13:10:40-04:00″,»modified»:»2019-03-21T03:44:36-04:00″,»deleted»:false,»fields»:[{«fieldId»:»0bc403e9000000000000000000000005c10d»,»content»:»»},{«fieldId»:»0bc403e9000000000000000000000005c10f»,»content»:»Fluid»},{«fieldId»:»0bc403e9000000000000000000000005c10e»,»content»:»Men»},{«fieldId»:»91c22871-0947-4f63-b067-4290ce18c0a0″,»content»:»Anupam»},{«fieldId»:»0bc403e9000000000000000000000005c111″,»content»:»»},{«fieldId»:»0bc403e9000000000000000000000005c110″,»content»:»»},{«fieldId»:»0bc403e9000000000000000000000005c113″,»content»:»All»},{«fieldId»:»0bc403e9000000000000000000000005c112″,»content»:»»},{«fieldId»:»0bc403e9000000000000000000000005c115″,»content»:»»},{«fieldId»:»0bc403e9000000000000000000000005c114″,»content»:» Новые поступления»},{«fieldId»:»0bc403e9000000000000000000000005c117″, «content»: «Никогда Mind»},{«fieldId»:»0bc403e9000000000000000000000005c116″,»content»:»»},{«fieldId»:»0bc403e9000000000000000000000005c0e8″,»content»:»»},{«fieldId»:»2b0a63f9-cb2d-4fc7-bcc5-06b30b59f8db»,»content»:»singh»}],»numSends»:0,»numBounces»:0,»numOpens»:0,»numClicks»:0,»numConversions»:0,»conversionAmount»:0}»,»message»:{}}»,»status»:200,»statusText»:»OK»}
Что я делаю не так, есть ли какая-то проблема с Magento 2?
Ответ №1:
В Magento 2 $resultJsonFactory
используется для возврата данных в формате JSON, и вы уже делаете то, что правильно. Но ответ переходит в функцию ошибки вашего AJAX-запроса, потому что с контроллера вы снова кодируете $contact
данные в JSON. Итак, просто удалите json_encode
, как показано ниже:
return $this->resultJsonFactory->create()->setData([
'success' => true,
'contact' => $contact,
'message' => $this->messageManager->addSuccessMessage("Successfully updated email preferences")
]);
вместо:
return $this->resultJsonFactory->create()->setData([
'success' => true,
'contact' => json_encode($contact),
'message' => $this->messageManager->addSuccessMessage("Successfully updated email preferences")
]);