How to display a php variable into html

前端 未结 5 615
萌比男神i
萌比男神i 2020-12-06 13:46

I just want to know how can I display a javascript variable into html?

Below is my php code:

var duration = ;
<         


        
相关标签:
5条回答
  • 2020-12-06 14:19
    document.getElementById('yourElementId').innerHtml = duration;
    
    0 讨论(0)
  • 2020-12-06 14:23

    Why don't use just display the php variable directly into the html?

    Lets just say $postduration echos "some." Here is the javascript code to echo "some":

    Here is <script>document.write(duration)</script> text.
    

    Here will be the output:

    Here is some text.
    
    0 讨论(0)
  • 2020-12-06 14:25

    No, wait, that's wrong. First of all, the javascript above does not "retrieve" anything from anywhere (neither php, nor anyplace else). Php generates the javascript, meaning that if $postduration is 5, you will get var duration = 5;, and if postduration = "test", you will get var duration = test; (which is invalid javascript and will crash/cause unwanted things to happen in your application.

    Last, to get a variable from javascript into html, you either replace the content of some other object (with innerHTML or something like that), or you create a new element and insert that into the page.

    Example here: http://jsfiddle.net/SLbKX/

    0 讨论(0)
  • 2020-12-06 14:30

    Here's a way to add a DIV to a page with the content of the DIV being the value of your PHP var:

     <script>
     var duration = <? echo $postduration; ?>;
     var div = document.createElement("DIV");
     div.appendChild(document.createTextNode(duration));
     document.body.appendChild(div);
     </script>
    
    0 讨论(0)
  • 2020-12-06 14:37

    Make your code more concise with jQuery:

    (1) Add this in your <head>:

    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    

    (2) Create an element where you want the variable to be displayed, and give it an ID, e.g.:

    <span id="printHere"></span>
    

    (3) Add this in your JavaScript:

    var duration="<?php echo $postduration ?>";
    $('#printHere').html(duration);
    

    For your PHP, try the following two options:

    <?=$postduration?>
    

    or...

    <?php echo $postduration; ?>
    
    0 讨论(0)
提交回复
热议问题