简体   繁体   English

将我的PHP变量值传递到Js文件

[英]Passing my PHP variable value to Js file

Hiii Everyone, 大家好,

<script src="../../record/recordmp3.js?id=<?php echo $_GET['id'];?>&&test_no=<?php echo $_GET['test_no'];?>"></script>

<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>

And I tried to get that passing value in recordmp3.js is 我试图在recordmp3.js中获得传递的值是

var student_id = this_js_script.attr('data-my_var_1');
var test_no = this_js_script.attr('data-my_var_2');

And also by 还有

var student_id = "<?php echo $_GET['id'];?>";
var test_no = "<?php echo $_GET['test_no'];?>";

And my value is not passing correctly.Instead only '0' is passing In my index page I have some PHP variable value I need to pass that value to recordmp3.js file.Please help me to solve this issue.Thank you so much in advance. 我的值没有正确传递,而是仅传递了'0'在我的索引页面中,我有一些PHP变量值,我需要将该值传递给recordmp3.js文件。请帮助我解决这个问题。非常感谢预先。

I tried like below its working fine 我尝试低于其正常工作

<script src="../../record/recordmp3.js"></script>
<script type="text/javascript"> 
MYLIBRARY.init(["<?php echo $id; ?>", "<?php echo $test_no; ?>"]); 
MYLIBRARY.helloWorld(); 
</script>

var MYLIBRARY = MYLIBRARY || (function(){ 
var _args = {}; // private 

return { 
init : function(Args) { 
_args = Args; 
// some other initialising 
}, 
helloWorld : function() { 
window.id=  _args[0]; 
window.test_no= _args[1];
} 
}; 
}());

You need to convert these values to json array. 您需要将这些值转换为json数组。 You cannot directly assign the php values to JavaScript variables. 您不能直接将php值分配给JavaScript变量。
Hope this answer is useful. 希望这个答案是有用的。 Please let me know if you find any difficulties on converting to json value. 如果您在转换为json值时遇到任何困难,请告诉我。

.js files don't execute and compile the php files,so in order to access the php variables in javascript the file should be .php . .js文件不会执行和编译php文件,因此,为了访问javascript中的php变量,文件应为.php

script.php script.php

<?php
  $foo = 'Hello cool';
?>
<script>
var foo ='<?php echo $foo ?>';
console.log(foo);
</script>

i hope this example will solve your issue 我希望这个例子能解决您的问题

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

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