如何将 phtml/php 文件中的变量传递给 js 文件


How to pass a variable in phtml/php file to js file?

这是关于Magento电子商务网站的。
我现在需要将一个变量从 view.phtml 传递给 product.js。

首先,我在php文件(view.phtml)中创建了一个if语句,以便从数据库中获取折扣率:

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,我需要将此变量$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 文件。

谁能帮忙?谢谢

更新 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,调用并使用它:

    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);
                }
            });

首先添加一个输入隐藏字段,并在 $ factor 变量初始化后为其分配$factor变量。然后通过javascript访问此变量

说在您的 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);        
        } 
?>
    <input type="hidden" id="factorDiscount" value="<?php echo $factor;?>"/> 
//Hidden field added here
<?php
  //If you have other codes place it here
?>

在 js 文件中使用

var factor = $("#factorDiscount").val();

我希望这就是你的意思伴侣. :)

如果你的外部js文件有.js扩展名,它可能不会被处理为php,php源代码将保留在那里,破坏javascript。

有几种方法可以解决此问题,例如:

  • 将 js 文件的扩展名更改为 .php ;
  • 通过页面脚本/magento传递变量,并检查它是否存在于外部js文件中。
  • 设置服务器以将所有.js文件处理为 php 文件;