简体   繁体   中英

Javascript function with vars on PHP print: quotes

I was just wondering if there is a better way to write down this PHP vars passed to a javascript function called inside a PHP print.:

while($nav = mysqli_fetch_array($nav_db)){
    print  '<li>
             <a href="#" onclick="getProductPage('.$nav['id'].', \''.$name.'\')">
                       '.$nav['Data'].'

             </a>
        </li>';
}

where

$nav['id']

is an INTEGER so I don't need extra '' for the JS, and

$name

is not an INTEGER so I need those \\' \\' for the JS.

Especially this step:

getProductPage('.$nav['id'].', \''.$name.'\')

Thank you

<?php while($nav = mysqli_fetch_array($nav_db)): ?>
  <li>
     <a onclick="getProductPage(<?php echo $nav['id']; ?>, '<?php echo $name; ?>')">
        <?php echo $nav['Data']; ?>
     </a>
  </li>
<?php endwhile; ?>

You should break out of PHP to write html. It is cleaner this way. Also, you had a rogue </span> in there and no need for a <br> in a <li> menu. Also, an a tag should have an href value in there, even if it is # or javascript:void(0) or something.

You should use json_encode to pass variables from php to javascript. That will make sure that there are no unescaped characters that can break your javascript.

So json_encode($name) instead of $name , etc.

For your example:

print  '<li>
         <a onclick="getProductPage(' . (int) $nav['id'].', ' . json_encode($name) . ')">
                   ' . htmlspecialchars($nav['Data']) . '

         </a>
    </li>';

have you considered using jquery and ajax send data to a php file and send back json_encode array to javascript?

example

after you send ajax call to php with datatype json, send back vars like this

$data['id'] = nav['id'];

echo json_encode($data);

or just $nav['id']

echo json_encode($nav)

in your javascript. on success, you can retrieve the id value like this

ajax{(
    blah,
    blah,
    ...
    success(msg){
    alert(msg.id)
    }
})

you can access the var as an object the code above will alert the value of the id. you can assign msg.id to a javascript var or pass it to a function ...ect

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