Jquery 如何从magento 2中的控制器获得ajax响应
我尝试进行ajax调用,并在controller中传递下拉值,然后在视图文件中获取特定的相关订单信息。响应实现,但如何在我的视图文件中利用该响应 这是我的phtml文件:Jquery 如何从magento 2中的控制器获得ajax响应,jquery,ajax,magento2,Jquery,Ajax,Magento2,我尝试进行ajax调用,并在controller中传递下拉值,然后在视图文件中获取特定的相关订单信息。响应实现,但如何在我的视图文件中利用该响应 这是我的phtml文件: <select id="chartOption"> <option value="">Select Option</option> <option value="status">Status</option> <option value="pa
<select id="chartOption">
<option value="">Select Option</option>
<option value="status">Status</option>
<option value="payments">Payments</option>
<option value="browser">Browser</option>
</select>
<input type="button" name="chart_button" value="Generate chart" onclick="click_chart()">
<div id="result"></div>
<script type="text/javascript">
function click_chart() {
var a = document.getElementById("chartOption");
var abc = a.options[a.selectedIndex].value;
data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "Blog/Post/Information",
data: "label=" + abc,
success: function (result) { jQuery('#result').html(result); },
error: function (error) { jQuery('#result').html(error); }
});
}
</script>
下面是如何执行此操作的示例,请根据您的要求进行修改 我用js模板来做这个 下面的示例将在phtml文件中创建下拉列表。您可以使用相同的方法以所需的格式显示数据 在你的JS中
define([
'jquery',
'underscore',
'mage/template',
'jquery/list-filter'
], function (
$,
_,
template
) {
function main(config, element) {
var $element = $(element);
$(document).on('click','yourID_Or_Class',function() {
var param = 'ajax=1';
$.ajax({
showLoader: true,
url: YOUR_URL_HERE,
data: param,
type: "POST",
dataType: 'json'
}).done(function (data) {
$('#test').removeClass('hideme');
var html = template('#test', {posts:data});
$('#test').html(html);
});
});
};
return main;
});
内部控制器
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);
}
}
在您的phtml文件中
<style>
.hideme{display:none;}
</style>
<div id='test' class="hideme">
<select>
<% _.each(posts, function(text,value) { %>
<option value="<%= value %>"><%= text %></option>
<% }) %>
</select>
</div>
.hideme{display:none;}
希望这会有所帮助。这是可行的,但magento不鼓励使用像$\u REQUEST这样的超全局变量。如果你想提交到市场,它将被拒绝。
<style>
.hideme{display:none;}
</style>
<div id='test' class="hideme">
<select>
<% _.each(posts, function(text,value) { %>
<option value="<%= value %>"><%= text %></option>
<% }) %>
</select>
</div>