简体   繁体   English

访问JavaScript中的PHP变量

[英]accessing php variable in javascript

http://192.168.21.189:8096/attend/supervisor/view_employee_attendence.php?eid=24 http://192.168.21.189:8096/attend/supervisor/view_employee_attendence.php?eid=24

i want to access eid=24 in javascript is there any way to access that... in php we can access it using 我想在javascript中访问eid = 24,有什么方法可以访问...在php中,我们可以使用

$eid=$_REQUEST['eid'];

so i was wondering that is there any way i can access that in my javscript... i want to use the value of eid to fetch data from mysql db using ajax 所以我想知道有什么办法可以在我的javscript中访问它...我想使用eid的值使用ajax从mysql数据库中获取数据

in your template, echo the value in a javascript variable: 在您的模板中,在javascript变量中回显值:

var id = '<?php echo $eid; ?>';

The quotes are not needed when you echo an integer. 回显整数时,不需要引号。

You can get the part after ? 你可以得到一部分? in URL using window.location.search and you have to manually parse it in JavaScript. 使用window.location.search在URL中输入,您必须在JavaScript中手动对其进行解析。 Similar question with the solution you need: https://stackoverflow.com/a/901144/1608594 您需要的解决方案的类似问题: https : //stackoverflow.com/a/901144/1608594

Example

    <?php
    $id = 1;
    ?>
    <script>
    var MyId = '<?php echo $id; ?>';
    </script>

Please use below javascript function to fetch querystring value in javascript. 请使用下面的javascript函数来获取javascript中的querystring值。

<script>
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

// query string value
var eid = getParameterByName('eid');
</script>

You can use it as a javascript variable globally. 您可以将其全局用作javascript变量。

<script>
    var eid = "<?php echo $eid;?>";
</script>
  <script>
    var yourId = '<php echo $_REQUEST['eid']; ?>';
  </script>

尝试这个:

var eid = window.location.search.substring(1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM