将PHP数组传递到JavaScript中进行循环



我正试图将一些值从PHP数组传递到JavaScript中。

我的php变量$contacts_info具有以下值。

Array ( [0] => Array ( [contact_id] => 20 [type_id] => 2 [contact_type] => Representative Phone [contact_value] => 0987654321 )
[1] => Array ( [contact_id] => 21 [type_id] => 4 [contact_type] => Shop Address [contact_value] => 0987654321 ) 
[2] => Array ( [contact_id] => 22 [type_id] => 3 [contact_type] => Emergency Phone [contact_value] => 0987654321 ) 
[3] => Array ( [contact_id] => 23 [type_id] => 2 [contact_type] => Representative Phone [contact_value] => 0987654321 ) 
[4] => Array ( [contact_id] => 24 [type_id] => 3 [contact_type] => Emergency Phone [contact_value] => 0987654321 ) 
[5] => Array ( [contact_id] => 25 [type_id] => 4 [contact_type] => Shop Address [contact_value] => 0987654321 ) ) 1

我正在尝试使用JavaScript在一些带有for循环的组合框中分配一个特定值。但我这样做有问题。

Type: ParseError
Message: syntax error, unexpected '<', expecting ']'

我的JavaScript代码:

<script>
var total_counter = "<?php echo $total_contact; ?>";
var contact_info = "<?php json_encode($contacts_info); ?>";
for (var i = 0; i <= total_counter - 1; i++) {
let element = document.getElementById("contact_type_id_" + i);
element.value = "<?php echo $contacts_info[<script>document.writeln(i);</script>]['type_id'] ?>";
}
</script>

问题出在<?php echo $contacts_info[<script>document.writeln(i);</script>]['type_id'] ?>这一部分。有人能帮我吗?

谢谢。

请执行以下操作,

  1. 您需要删除PHP脚本中的双引号,因为""将其视为字符串。

  2. <?php echo json_encode($contacts_info); ?>缺少echo,因为JSON数组没有得到响应,因此无法将其分配给javascript变量contact_info

  3. 变量contact_info已经有了JSON数组,无需再次从PHP变量中获取

最终,您的代码应该看起来像

<script>
var total_counter = <?php echo $total_contact; ?>;
var contact_info = <?php echo json_encode($contacts_info); ?>;
for (var i = 0; i <= total_counter - 1; i++) {
let element = document.getElementById("contact_type_id_" + i);
element.value = contact_info[i].type_id ;
}
</script>

相关内容

  • 没有找到相关文章

最新更新