简体   繁体   中英

Cannot get cookie made in PHP in JavaScript file

I am trying to get the username a user enters in an input box in a php file as a cookie, then in a JS file read that cookie and get the username.

PHP

<?php
...
   print('<form method="POST" name="loginForm" action="myDomain.com">' . "\n");
   print('              <div class="loginContainer">' . "\n");
   print('                              <label for="userNameBox"><b>Account Login: </b></label>'. "\n");
   print('          <input type="text" class="userName"id="userNameBox" placeholder="Enter Username" required="required">'. "\n");
   print('          <input type="button" class="loginButton" id="loginButton" value="Login"/>' . "\n");
   print('        </div>'. "\n");
   print('</form>' . "\n")
   print('     <div id="toolbar">' . "\n");

...
setcookie ( "LOGIN_USERNAME_COOKIE", 
            $_POST['userNameBox'] , 
            $expires = 0, 
            $path = "/" , 
            $domain = 'myDomain.com' ,
            $secure = false,
            $httponly = false 
          );
...
?>

JavaScript (just trying to print out the cookie)

confirm("Username entered: "+document.cookie.split('LOGIN_USERNAME_COOKIE=')[1]);

In the confirm Java alert I get this:

Username entered: __utma=261946002.205893547.1618416838.1618416838.1618416838.1; __utmc=261946002; __utmz=261946002.1618416838.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmt=1; __utmb=261946002.1.10.1618416838; _fbp=fb.1.1618416838418.1117675244

how can I fix this to get the cookie to contain the text the user enters and display it?

Try this:

let username = document.cookie
  .split('; ')
  .find(row => row.startsWith('LOGIN_USERNAME_COOKIE='))
  .split('=')[1];

confirm("Username entered: "+username);

Source: MDN

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