当前位置: 代码迷 >> JavaScript >> 如何在javascript函数中使用php的mysql数据库中的值
  详细解决方案

如何在javascript函数中使用php的mysql数据库中的值

热度:89   发布时间:2023-06-05 15:56:12.0

在php中,我使用了sql查询来获取数据:-

$sql="Select * from xyz";

$result = $conn->query($sql);
    // output data of each row
    while($row = $result->fetch_assoc()) {
       error_log( "id" . $row["id"]);

    }

现在,我想使用在javascipt函数中使用$ row [“ id”]获得的所有值,并将其用于变量中(可以说var j)。 这个怎么做?

尝试这样的事情:

<?php

$sql="Select * from xyz";
$errorsData = array();
$result = $conn->query($sql);
    // output data of each row
    while($row = $result->fetch_assoc()) {
       error_log( "id" . $row["id"]);
       $errorData[]=$row["id"]
    }
$errorJson = json_encode($errorsData);

?>

<script>

   var errorJson = <?= $errorJson ?> ;

   console.log(errorJson);

<script>

祝好运!!

在jQuery中,我会这样做,

PHP

$sql="Select * from xyz";
$arr_json = array();
$result = $conn->query($sql);
    // output data of each row
    while($row = $result->fetch_assoc()) {
       error_log( "id" . $row["id"]);
       $arr_json[] = $row['id'];
    }

回声json_encode($ arr_json);

jQuery的

$.get(
  <THAT CALLED URL>,
  function(ret_data){
     console.log(ret_data);
     /* you can use the ret_data as ret_data.<INDEX> */
  }
);
  相关解决方案