Json_encode不显示任何在我的外部javascript

json_encode not showing anything in my external javascript

本文关键字:我的 外部 javascript 任何 显示 encode Json      更新时间:2023-09-26

我得到了我的PHP页面它是从mysql中fetchong一个数组我想用json_encode将这个数组移动到javascript中这是我的PHP页面

 echo "<script type='text/javascript' src='javascript1.js'></script>";
 $result = mysqli_query($con,"SELECT l_longitude,l_latitude FROM register_complain");

 echo "<table border='1'>
 <tr>
  <th>Latitude</th>
 <th>Longitude</th>
 </tr>";
    while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['l_longitude'] . "</td>";
    echo "<td>
    " . $row['l_latitude'] . "</td>";
    echo "</tr>";
    echo $ab = $row['l_latitude'];
    echo $ab2 = $row['l_longitude'];
     echo json_encode( $ab );
    echo "</table>";
 header('Location:http://localhost/cca/View_Map.html');  
mysqli_close($con);

和我的外部javascript1.js

  var db_array = <?php echo json_encode($ab); ?>;
  alert(db_array);

但是当我在javascript页面中使用var db_array时它不会显示带有值

的警告消息

尝试在您的PHP页面中首先设置$ab值为javascript变量,然后包含您的js

echo "<script>var db_array = '". json_encode($ab)."';</script>
<script type='text/javascript' src='javascript1.js'></script>";

和alert在js文件

你要做的是创建一个php脚本,把你的javascript代码放在其中,在你需要动态部分的地方放上你的php代码,或者在那里返回你的东西(处理应该在输出任何东西之前进行)

renderJS.php

<?php
    //code code code
    $data = someFunctionThatCreatesData();
    //more code code code
    //Makes it so browsers know this is actually a js file
    header('Content-Type: text/javascript');
?>
//Begin JS
var db_array = <?php echo json_encode($data); ?>;
alert(db_array);

然后在html中将脚本标签src指向php文件

<script type="text/javascript" src="renderJS.php"></script>

如果你的处理是在同一个文件中作为你的html代码那么只要做Rakesh Sharma在他的回答和输出<script>标签然后你的js代码然后关闭</script>标签在同一文件(通常你是在你的头标签回声)

我自己也在做很多类似的事情,但我用的是另一种方式。我倾向于使用jQuery,因为它会让我的工作更轻松。我通常是这样做的:

PHP脚本
<?php
//...
//... get the database results into $result array
//...
// output results as JSON
header("Content-Type: application/json");
print json_encode($result);
exit();
Javascript (jQuery)
$.getJSON('path/to/above/file.php', function(data) {        
    // alert(data) will only show [Object object]
    // as with the correct header set it will return
    // a Javascript Object/Array
    console.log(data);
});

当Javascript代码运行时,它将启动对PHP文件的AJAX请求,并返回编码的数据。