2017-04-22 47 views
1

如何在Java文件中获取PHP变量在PHP文件中的脚本代码?这段代码在一个PHP while循环中,所以我知道我必须以某种方式为每个JS属性赋予一个来自mysql结果的$ id,并将它们传递给html的输入,这样每个html标记都将独立于彼此。来自MySQL while循环的JavaScript和HTML标记的变量

这里是PHP文件代码:

<script> 
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> 
</script> 

while ($row = mysql_fetch_array($query)) 
{ 
$id = $row['id']; 

<select name='alarm_action' id="alarm_action" required> 
    <option value="">Default Action</option> 
    <option value='Play Sound'>Play Sound</option> 
    <option value='Say This'>Say This</option> 
    <option value='Run Command'>Run Command</option> 
    <option value='Run Program'>Run Program</option></select> 
<input name="file_path" id="file_path" type="text" style="display: none" required/> 




<script> 
var alarmInput = $('#alarm_action'); 
alarmInput.on('change', function() { 
    var file_path = $('#file_path'); 
    file_path.show(); 
    switch ($(this).val()) { 
    case 'Play Sound': 
    case 'Run Program': 
     file_path.attr('type', 'file'); 
     break; 
    case 'Say This': 
    case 'Run Command': 
     file_path.attr('type', 'text'); 
     break; 
    case '': 
    file_path.hide(); 
    break;      
    } 
}); 
</script> 

} 

回答

1

只需使用

<?php 

$id = $row['id']; 

?> 
<!-- html --> 
<p><?php echo $id; ?></p> 

添加在JavaScript

<script> 
//var id = <?php echo $id; ?> 
var alarmInput = $('<?php echo $id; ?>'); 
alarmInput.on('change', function() { 
    var file_path = $('#file_path'); 
    file_path.show(); 
    switch ($(this).val()) { 
    case 'Play Sound': 
    case 'Run Program': 
     file_path.attr('type', 'file'); 
     break; 
    case 'Say This': 
    case 'Run Command': 
     file_path.attr('type', 'text'); 
     break; 
    case '': 
    file_path.hide(); 
    break;      
    } 
}); 
</script> 

所以它只是使用<?php echo $id; ?>,在标签内要但不要忘记打开和关闭php标签

+0

我将如何将它用于java脚本?你可以在JS中使用php标签吗? – Vlad

+0

是的,我会写一个例子 –

+0

好吧谢谢,我修理了只是添加php标签,它打破了JS代码 – Vlad