2013-05-02 53 views
0

这是arrivalPlay.php。如果用户单击来自arrivalRead.php的数据并使url变成arrivalPlay.php?id = 1(2,3,4,5等等),则加载此页面。使用jquery从动态php页面检索数据到javascript

<?php 
    $con = mysqli_connect("localhost","admin","admin","flight_status"); 
    $id = $_GET['id']; 
    $getrow = mysqli_query($con, "SELECT * FROM arrival WHERE id='$id'"); 
    $row = mysqli_fetch_array($getrow); 
    mysqli_close($con); 
    $order = array(1,2,3,4); 
    foreach ($order as $o) { 
     $res[$o][f] = $row[$o]; 
    } 
    json_encode($res); 
?> 

这是getData.js文件。该文件文件接收res并将被传递给'mp'。

<script> 
    function aha() { 
    $.ajax({ 
     url:'arrivalPlay.php', 
     data:{id:3}, 
     dataType:'json', 
     type:'GET', 
     success:function(data){ 
      document.write(data[1].f); 
      document.write(data[2].f); 
      document.write(data[3].f); 
      document.write(data[4].f); 
     } 
    }); 
    } 
</script> 

页arrivalPlay.php只有数据如果URL成为arrivalPlay.php?ID = X。有没有办法从'动态'的PHP检索到JavaScript页面的数据?如果您认为这很奇怪,请随时改变我的方法。谢谢...

回答

0

试试这个:

首先在服务器页面之前json_encode($res);

申请echo应该echo json_encode($res);

然后,如果它不工作,然后尝试这个代码

<script> 
$(document).ready(function(){ 
    $(document).on('click','#a',function(e){ 
     e.preventDefault(); 
     $.ajax({ 
      url:'arrivalPlay.php', 
      data:{id:1}, 
      dataType:'json', 
      success:function(data){ 
       $('#res').html(data); 
      } 
     }); 
    }); 
}); 
</script> 

如果你想从服务器json那么只有json data应该是从server

就像在你的代码通过

<?php 
    $con = mysqli_connect("localhost","admin","admin","flight_status"); 
    $id = $_GET['id']; 
    $getrow = mysqli_query($con, "SELECT * FROM arrival WHERE id='$id'"); 
    $row = mysqli_fetch_array($getrow); 
    mysqli_close($con); 
    $res=array(); 
    $order = array('airline','flight','origin','status'); 
    foreach ($order as $o) { 
     $res[$o] = $row[$o]; 
    } 
    echo json_encode($res);// echo the json string 
    // remember that no other output should be generated other than this json 
    return; //so you can use this line 
?> 

足够

你不想做json那么您使用此代码

echo implode(',',$res);,而不是echo json_encode($res);

也在javascript在这种情况下删除此选项dataType:'json',

jquery.ajax

+0

对不起,对于迟到的答案。回显确实打印了'$ res'的内容。上面的代码不起作用,我的JavaScript不加载任何东西。我想知道为什么。 – epndkempot 2013-05-03 00:32:32

+0

@epndkempot在使用之前,请尝试上面的操作,并检查是否已添加'jquery'的任何'版本'。 – 2013-05-03 04:43:30

+0

感谢您的建议。我使用json并删除不必要的元素。在接收端,现在可以打印“null - 1 null - 2 null - 3 null - 4”。如果我更改为'$ .getJSON('arrivalPlay.php?id = 1',它将检索数据。 – epndkempot 2013-05-03 06:45:21

0

既然您收到JSON数据,我怀疑你想将它们放入一个HTML元素。我要么改变我的PHP文件来生成HTML元素,要么执行som javascript逻辑来创建基于服务器提供的JSON数据的元素。

+0

谢谢...我将$ res数据存储到一个数组。现在我打算在js中接收它 – epndkempot 2013-05-03 01:08:49