简体   繁体   中英

How to access a php variable into external .js(my.js) file

How can I gain access to a PHP variable from an external javascript (my.js) file? I want to get the dynamic id or class into external js file

PHP

<div id="tabs<?php echo str_replace(' ', '',$child1['id']); ?>" class="<?php  echo $activetab1; ?> tab-pane">
    <?php if ($child1['children1']) { $category2=$child1['children1'];  ?>
    <ul class="tabs<?php echo str_replace(' ', '',$child1['id']); ?>" id="tabs<?php echo str_replace(' ', '',$child1['id']); ?>" data-count="15">
        <?php foreach ($category2 as $child2) { ?>
        <li>
            <?php echo $child2['name']."------------main"; ?>
        </li>
        <?php if ($child2['children9']) { $category9=$child2['children9'];  ?>
        <?php foreach ($category9 as $child9) { ?>
        <li>
            <?php echo $child9['name']; ?>
            <?php echo str_replace(' ', '',$child1['id']); ?>
        </li>
        <?php } } ?>
        <?php }  ?>
    </ul>
    <?php }  ?>
</div>

External JavaScript

var container = $("ul.tabs25"),
count = container.data("count"),
column;

container.children().each(function(index) { 

  if (index % count == 0)
    column = $("<li/>").css({"float": "left", "margin-right": "50px"}).appendTo(container);

  var hello=$(this).appendTo(column);
  console.log(hello);
});

I want to dynamically change this $child1['id'] within JavaScript.

You can access data from php script in Javascript (I'll use jQuery here) like this

Create input hidden field within you php file like this

<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />
in your javascript file:

var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}

This will do the job

A simple way to do this is to create an inline script with PHP. Something like:

<script type="text/javascript">
    var myid=<?php echo str_replace(' ', '',$child1['id']); ?>;
</script>

This way myid is included in the html output of PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM