apeend jquery元素,其中包含动态php代码

bqucvtff  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(235)

我想附加100个span元素,其中应该包含动态php代码,以便从wordpress数据库获取数据。我正在尝试下面的代码,但它不适合我,请给我一些建议。

$(document).ready(function(){
  var i = 1;
  while (i <= 100) {
    $(".peak").append("<span class='<?php echo $result[0]-column"+i+";?>'><?php echo $result[0]->column"+i+";?><span>");
    i++;
  }
});

产出应该是,,
column1[data]
column2[data]
<span class='column3[data]>column3[data]
等等
如果我删除“i”增量,这段代码工作得很好,

var i = 1;
  while (i <= 100) {
    $(".peak").append("<span class='<?php echo $result[0]->column1;?>'><?php echo $result[0]->column1;?></span>");
    i++;
  }
35g0bw71

35g0bw711#

首先,您可以尝试使用php显示数据:

<?php

$result = [ // get result from db;
  0 => [
    "column1" => [
      "data" => "a"
    ],
    "column2" => [
      "data" => "b"
    ],
    "column3" => [
      "data" => "c"
    ],
  ]
];

echo "<div class=\"peak\">\n";
  foreach ($result[0] as $key => $value) {
    echo "\t<span class=\"$value[data]\">$value[data]<span>\n";
} 
echo "</div>\n";

输出:

<div class="peak">
  <span class="a">a<span>
  <span class="b">b<span>
  <span class="c">c<span>
</div>

第二种方法是ajax index.php :

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <script
    src="https://code.jquery.com/jquery-3.6.0.min.js"
    integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
    crossorigin="anonymous">
  </script>
  <style type="text/css">
    .peak span {
      margin-right: 5px;
    }
  </style>
</head>
<body>
<div class="peak">
  <span>loading...</span>
</div>

<script>
  $(document).ready(function(){ 
    $.ajax({
      url: '/get_data.php',
      method: 'get',
      dataType: 'json',
      success: function(result){
        $('.peak').empty() //  remove children (span 'loading...')    

      // next forEach extract key as "column$i" 
      // and value as [ data=> a] etc. in php 
      Object.entries(result[0]).forEach(([key, value]) => {
          //next line get value.data or (result[0].column$i[data] in php)
          const {data} = value;
          const span = $('<span />').attr('class', data).html(data);
          $('.peak').append(span);
        })
      }
    });
  })
</script>
</body>
</html>

mock 例如 get_data.php :

<?php
header('Content-Type: application/json');

$result = [
  0 => [
    "column1" => [
      "data" => "a"
    ],
    "column2" => [
      "data" => "b"
    ],
    "column3" => [
      "data" => "c"
    ],
  ]
];

echo json_encode($result);

相关问题