我在PHP中有一个变量,我需要在我的JavaScript代码中使用它的值.如何将我的变量从PHP变为JavaScript?
我的代码看起来像这样:
<?php
...
$val = $myService->getValue(); // Makes an API and database call
?>
Run Code Online (Sandbox Code Playgroud)
我有需要的JavaScript代码,val并且看起来如下:
<script>
myPlugin.start($val); // I tried this, but it didn't work
<?php myPlugin.start($val); ?> // This didn't work either
myPlugin.start(<?=$val?> // This works sometimes, but sometimes it fails
</script>
Run Code Online (Sandbox Code Playgroud) 我正在使用PHP删除记录.我想使用JQuery UI对话框来确认操作,但我不知道如何将变量(我的RecordID)传递给重定向URL函数,或者允许URL访问window.location.href.
$("#confirm" ).dialog({
resizable: false,
autoOpen: false,
modal: true,
buttons: {
'OK': function() {
window.location.href = 'url and myvar??';
$( this ).dialog( "close" );
},
'Cancel': function() {
$( this ).dialog( "close" );
}
}
});
$("#delete").click(function() {
$("#confirm").dialog( "open" ).html ( "Are U Sure?" );
return false;
});
Run Code Online (Sandbox Code Playgroud)
HTML
<a href='index.php?recordid=$row[recordid]' id='delete'>DELETE</a>
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
所以我从数据库中检索了一系列记录.数组采用格式;
$rows[0]['id']=1;
$rows[0]['title']='Abc';
$rows[0]['time_left']=200;
$rows[1]['id']=2;
$rows[1]['title']='XYZ';
$rows[1]['time_left']=300;
//And so on upto 10-20 rows
Run Code Online (Sandbox Code Playgroud)
将此数组传输到我的javascript代码的最佳方法是什么?我希望javascript能够循环遍历所有记录,并使用'id'属性,用一些信息更新带有该id的div.
我的javascript代码在外部.js文件中,但我能够在我的页面的HTML代码中执行php代码.所以我可以这样做:
在my_file.js中:
var rows=New Array();
Run Code Online (Sandbox Code Playgroud)
在HTML代码中:
<html>
<head>
<script type="text/javascript" src="js/my_file.js"></script>
<script type="text/javascript">
<? foreach ($rows as $row):?>
<? extract($row);?>
rows[<?=$id;?>]['title']="<?=$title;?>";
//And so on
<? endforeach;?>
</script>
Run Code Online (Sandbox Code Playgroud)