开发者

JS variable scope and script sources

I have a variable defined in script tags within the head of the document:

<?php if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) {
    echo '<scrip开发者_JAVA百科t>var userdir = '.$_SESSION['user']->directory.'</script>';
} ?>

after that I include several javascript files, one of which includes a function which includes

if (type == 'image'){
   var imgElement = elementId.replace(/upload_/, "img_");
   $('#'+imgElement).attr("src", "assets/uploads/"+ userdir +"/images/" + vidfile);
}

userdir is defined within the document if I view source, but the image path that comes back is 'undefined'. shouldn't it be getting the value?


You almost certainly need to include quotes around the assignment to userdir.

echo '<script>var userdir = "'.$_SESSION['user']->directory.'";</script>';


Anything defined outside of a function is going to be a global variable. I assume the variable you are defining in the document is such a global variable. That global variable should be available inside of any function. I'm assuming your include files are made of functions. If the global values have actually been defined and you can't access them within the functions or the js files then I would question the order of when things are loading.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜