如何将PHP(index.PHP文件)变量值传递到外部JAVASCRIPT.js文件?
实际上,这段代码是在如何将PHP(index.PHP文件)变量值传递到外部JAVASCRIPT.js文件?,javascript,php,jquery,Javascript,Php,Jquery,实际上,这段代码是在index.php文件中编写的,但现在我想将这个javascript数组值传递给外部js文件 <?PHP $qry2 = mysql_query("SELECT table_no FROM table_info"); while($res2 = mysql_fetch_array($qry2)) { static $i = 0; $i++; $reg_table[$i] = $res2['table_no']; } ?>
index.php
文件中编写的,但现在我想将这个javascript数组值传递给外部js文件
<?PHP
$qry2 = mysql_query("SELECT table_no FROM table_info");
while($res2 = mysql_fetch_array($qry2))
{
static $i = 0;
$i++;
$reg_table[$i] = $res2['table_no'];
}
?>
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
var bookedSeats=新数组();
预订座位。按(“”);
我希望bookedSeats
变量位于外部table.js
文件中。您在那里有jQuery标记,因此我将给您这个。。。使用Ajax:
test.php
<?php
// Handle Ajax Request
if (isset($_GET['loadData']))
{
// Query your db here, im building dummy data
$results = array();
for ($i = 0; $i < 10; $i++) {
$results[] = 'Data '. $i;
}
// Return Data
exit(json_encode($results));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// Load Data Via Ajax
$.getJSON("test.php?loadData", function(bookedSeats)
{
console.log(bookedSeats);
});
</script>
//通过Ajax加载数据
$.getJSON(“test.php?loadData”),函数(bookedSeats)
{
控制台日志(预订座位);
});
当页面加载时,我们得到如下结果:
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
在
之后,…
是可以的,但是只有在您推迟其执行的情况下,才可以将其放在前面-放在后面更安全;) 即使Latheesan Kanes的解决方案是正确的,我最终还是会为您提供一个替代方案
如果您可以访问table.js文件中Javascript对象中的构造函数,那么我的示例只是一个简单的例子
<script>
var bookedSeats = new Array();
person=new Object();
<?php foreach($reg_table as $key => $val)
{
// here a javascript object
?>
person.firstname="John"; // of course replace firstname and John by your informations
<?php }?>
// then call table.js constructor
var objectInTableDotJS = new YourConstructor(person); // now in table.js you need to make modification :)
var bookedSeats=新数组();
person=新对象();
person.firstname=“John”//当然,用你的信息代替名字和约翰
//然后调用table.js构造函数
var objectInTableDotJS=新的构造函数(person);//现在在table.js中,您需要进行修改:)
只需在和reference bookedSeats之后包含table.js,还有,为什么要引用外部脚本
munna.js
,然后继续内联编写代码?在Table.js中,您的所有代码都是Javascript,但变量的内容来自php文件,因此它非常动态。您可以简要介绍json以及如何解析它。
<script src="external.js"></script>
<script>
var bookedSeats = new Array();
person=new Object();
<?php foreach($reg_table as $key => $val)
{
// here a javascript object
?>
person.firstname="John"; // of course replace firstname and John by your informations
<?php }?>
// then call table.js constructor
var objectInTableDotJS = new YourConstructor(person); // now in table.js you need to make modification :)