简体   繁体   中英

Generate random string using javascript function

I have the following code within the <script> tags, which are within the <head> tags of my HTML file;

function generateUMR($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
} 

Within the <body> tags, I have the following line of code in order to output the randomly generated string;

echo '<script type="text/javascript"> generateUMR(); </script>';

I have been trying for a few hours now but I am receiving no output from this code, yet no errors, could someone please tell me where I am going wrong?

Thanks in advance.

Your function is treated as a string, you need to concatenate the function call like so.

echo '<script type="text/javascript"> ' . generateUMR() . ' </script>';

In order to see the result in the browser, you will need to view the HTML source because the browser won't show the content of a script tag. It doesn't really make sense to output this into a script tag, because it's just a random string, try some other tag such as <p></p> instead.

If you are trying to call the PHP function from the client side, then that won't work. You'll need to use AJAX to do that.

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