Речь идет о веб-сайте Magento для электронной коммерции.
Теперь мне нужно передать переменную из view.phtml в product.js.Как передать переменную в файл phtml/php в файл js?
Во-первых, я создал, если оператор в файле PHP (view.phtml) для того, чтобы получить дисконтная ставка формирует базу данных:
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
//echo $customerData->getemail();
$conn = Mage::getModel('core/resource')->getConnection('core_read');
$sql = 'select max(sl.discount_amount) from salesrule sl
join salesrule_customer_group scg on scg.rule_id = sl.rule_id
join customer_entity ce on ce.group_id = scg.customer_group_id
where ce.email = "'.$customerData->getemail().'";';
$results = $conn->fetchAll($sql);
//echo $results;
}
else
{ $factor = 100;} //only apply to NOTLOGGED IN's custom option price label
foreach ($results as $result){
{ $factor = $result['max(sl.discount_amount)'];
}
//echo '<small> Discounted price: </small> $',$prices*($factor/100);
}
Как вы видите, метод перенастройки в $ фактор, как результат , и мне нужно передать этот переменный $ factor в файле product.js (javascript).
var subPrice = 0;
var subPriceincludeTax = 0;
//var a = test;
Object.values(this.customPrices).each(function(el){
if (el.excludeTax && el.includeTax) {
subPrice += parseFloat(el.excludeTax); // this will affect the price when changing option *important
//so need to change somewhere else in the same time to full fill the requirementirement
// but it doesn;t change to backend value
subPriceincludeTax += parseFloat(el.includeTax);
} else {
subPrice += parseFloat(el.price);
subPriceincludeTax += parseFloat(el.price);
}
});
excl += subPrice;//also affect the final price *frontEnd
incl += subPriceincludeTax;
Я попытался передать его JSON, но он вообще не работает, и я не могу понять причину. У меня есть что-то вроде echo json_encode($factor);
, чтобы проверить вывод, и он выглядит отлично, но все же не может перейти во внешний файл js.
Может ли кто-нибудь помочь? Спасибо
UPDATE 1: В PHP файл я добавил следующие:
var optionsPrice = new Product.OptionsPrice(<?php echo $this->getJsonConfig() ?>);
var tester = "<?php echo json_encode($factor);?>"
</script>
И передать эти коды в JS, как:
var subPrice = 0;
var subPriceincludeTax = 0;
var tester = tester;
//var a = test;
Object.values(this.customPrices).each(function(el){
if (el.excludeTax && el.includeTax) {
subPrice += parseFloat(el.excludeTax)*tester; // this will affect the price when changing option *important
//so need to change somewhere else in the same time to full fill the requirementirement
// but it doesn;t change to backend value
subPriceincludeTax += parseFloat(el.includeTax);
} else {
subPrice += parseFloat(el.price);
subPriceincludeTax += parseFloat(el.price);
}
});
excl += subPrice;//also affect the final price *frontEnd
incl += subPriceincludeTax;
Но это не кажется для работы: (
ОБНОВЛЕНИЕ 2 Согласно outlooker я попытался добавил тип входа в файле PHTML, как это:
<script type="text/javascript">
var optionsPrice = new Product.OptionsPrice(<?php echo $this->getJsonConfig() ?>); //the var of the option price, disable to disable price options
**<input type="hidden" id="factorDiscount" value="<?php echo $factor;?>"/>**
</script>
Потом я также реализации вар в файл JS, вызов и использовать его, а также:
var subPrice = 0;
var subPriceincludeTax = 0;
var factor = $("#factorDiscount").val();//is not global
Object.values(this.customPrices).each(function(el){
if (el.excludeTax && el.includeTax) {
subPrice += parseFloat(el.excludeTax)*factor; // this will affect the price when changing option *important
subPriceincludeTax += parseFloat(el.includeTax);
} else {
subPrice += parseFloat(el.price);
subPriceincludeTax += parseFloat(el.price);
}
});
Сейчас это не работает, но я понимаю, что вы имеете в виду, но я не могу правильно вставлять коды. Есть комментарии? Сэр. Спасибо
ОБНОВЛЕНИЕ 3 Благодарю вас за помощь, сэр. Я вставил код в файле PHTML отлично, но когда я пытаюсь использовать его, не кажется, что получает данные из PHP
var subPrice = 0;
var subPriceincludeTax = 0;
var factor = $("#factorDiscount").val();//I declare the var here
Object.values(this.customPrices).each(function(el){
if (el.excludeTax && el.includeTax) {
subPrice += parseFloat(el.excludeTax)*factor; // trying to times the var factor with the price but don't know if i am doing the right things.
subPriceincludeTax += parseFloat(el.includeTax);
} else {
subPrice += parseFloat(el.price);
subPriceincludeTax += parseFloat(el.price);
}
});
сохранить значение в скрытом поле и получить доступ к нему через javascript – Outlooker
ум, чтобы дать мне более подробную информацию? – anson920520