Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

javascript - wp_localize_script Function not Working: Followed Similar Questions Solutions

In functions.php I have put as below:

    function wp12311_enqueue_scripts() {
     wp_enqueue_script( 'wp12311-scripts',  get_stylesheet_directory_uri() . '/test/scripts-test.js', array( 'jquery' ), false, true );
     wp_localize_script( 'wp12311-scripts', 'userDetails', array(
         'current_user' => wp_get_current_user()
     ) ) ;
}
add_action( 'wp_enqueue_scripts', 'wp12311_enqueue_scripts' );

Then, in /test/scripts-test.js I have below code:

    var userEmail = userDetails.current_user.username.data.user_email;
console.log("display is " + userEmail);

In my HTML file I have below code:

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript" src="/test/scripts-test.js"></script>

    <title>Test</title>

    <link href="https://fonts.googleapis.com/css?family=Dosis:400,700" rel="stylesheet" />
    <link href="style.css" rel="stylesheet" />



  </head>

  <body>

</body>


</html>

When I load the html file, I get the error:

scripts-test.js:3 Uncaught ReferenceError: userDetails is not defined

Please let know what is the issue and how can I make it work. Thanks.

question from:https://stackoverflow.com/questions/65858534/wp-localize-script-function-not-working-followed-similar-questions-solutions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are calling it too early, try to wait until document is ready. and it's better to use the global window object

jQuery(document).on( 'ready', function() {
    var userEmail = window.userDetails.current_user.username.data.user_email;
    console.log("display is " + userEmail);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...