简体   繁体   中英

combine php code with jquery/javascript

I have php code and jQuery/javascript. I want to make visitor counter using jQuery and php code.

Here is the php code :

<?php 
$handle = fopen("counter.txt", "r");

if(!$handle){
    echo "could not open the file" ; 
} else { 
    $counter = (int ) fread($handle,20); 
    fclose ($handle);
    $counter++; 
    //echo $counter; 
    $handle = fopen("counter.txt", "w" ); 
    fwrite($handle,$counter) ; 
    fclose ($handle) ; 
} 
?>

and this is jQuery/javascript code :

<html>
<head>
<title>jQuery Hello World</title>

<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/jquery.counter.js"></script>

<link href="js/jquery.counter-analog.css" rel="stylesheet">

</head>

<body>

  <span id="custom"></span>
  <script>
     $('#custom').addClass('counter-analog').counter({
       //direction: 'up',
       interval: '1',
       format: '99999'
       //stop: '2012'
    });
  </script>
</body>
</html>

How can I combine the jQuery/javascript code into php code? This is my first time for using jQuery, and I still don't understand to use jQuery. So I need your help. :D Thank you.

This is the result:

在此处输入图片说明

I want to add "50" into the jQuery "00000", so the result is "00050"

You simply need to echo the counter value in the span element. So assuming your PHP code is at the top of the file, it should look like this.

<?php 
$handle = fopen("counter.txt", "r");

if(!$handle){
    echo "could not open the file" ; 
} else { 
    $counter = (int ) fread($handle,20); 
    fclose ($handle);
    $counter++; 
    //echo $counter; 
    $handle = fopen("counter.txt", "w" ); 
    fwrite($handle,$counter) ; 
    fclose ($handle) ; 
} 
?>
<html>
<head>
<title>jQuery Hello World</title>

<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/jquery.counter.js"></script>

<link href="js/jquery.counter-analog.css" rel="stylesheet">

</head>

<body>

  <span id="custom"><?php echo $counter; ?></span>
  <script>
     $('#custom').addClass('counter-analog').counter({
       //direction: 'up',
       interval: '1',
       format: '99999'
       //stop: '2012'
    });
  </script>
</body>
</html>

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