0

我正在做一些事情,我已经从各地剪断了代码,但很难让它工作。

所以我想要做的是让一个页面通过 ajax/json/php 请求另一个页面并查询一个数据库,然后返回多个结果并在第一页上打印出来。

我的问题是,每当我运行 client.php 页面时,我只能返回

id:[对象对象] 名称:[对象对象]

而不是我想要的数据,我知道这可能只是某个地方的一个愚蠢的小错误,所以任何帮助将不胜感激。

在我因使用 mysql 而不是 mysqli 而受到质疑之前,这只是我使用的代码来自http://openenergymonitor.org/emon/node/107

客户端.php

    <html>
    <head>
         <script language="javascript" type="text/javascript" src="jquery.js"></script>
    </head>
    <body>

    <h2> Client example </h2>
    <h3>Output: </h3>
        <div id="output">this element will be accessed by jquery and this text    replaced</div>

    <script id="source" language="javascript" type="text/javascript">

    $(function () 
    {
    $.ajax({                                      
    url: 'api.php',                  //the script to call to get data          
    data: "",                        //you can insert url argumnets here to pass to   api.php
                                   //for example "id=5&parent=6"
    dataType: 'json',                //data format      

  success: function(data)          //on recieve of reply
    {

     var id = data[0];              //get id
     var vname = data[1];           //get name

     $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html

     }
     });
     }); 

     </script>
     </body>
     </html>

api.php

    <?php 

     $host = "localhost";
     $user = "root";
     $pass = "";
     $databaseName = "abeiq_stock";
     $tableName = "variables";

     $con = mysql_connect($host,$user,$pass);
     $dbs = mysql_select_db($databaseName, $con);


     $query = "SELECT * FROM $tableName";
     $result = mysql_query($query);

     $rows = array();

     while($r = mysql_fetch_assoc($result)){
     $rows[] = $r; has the same effect, without the superfluous data attribute
     $rows[] = array('data' => $r);
      }

       echo json_encode($rows);

     ?>
4

2 回答 2

1

You're sending back an entire array of objects. This JavaScript is completely wrong:

var id = data[0];              //get id
var vname = data[1];           //get name

It should be something like...

var id = data[0].data.id
var vname = data[0].data.id

Obviously, loop through instead of hard coding 0, but you get the idea.

You should also learn to do some basic debugging. If you use console.log(data) in your jQuery callback, you can see what is being deserialized. Also, you can use your browser tools to see the raw request/response data. If you learn to debug a bit, you could solve this quickly.

And, why are you adding the data to $rows twice? Don't do that.

于 2013-06-14T04:59:51.973 回答
0

我知道这是在 6 月份,并且很有帮助,但真正帮助我理解或至少更好地导航 JSON 的是它的stringify方法:

JSON.stringify(SOME_JSON_OBJECT);

正如您可以清楚地看到您传入的成为对象的内容,这会将其作为对象的所有 JSON 元素的字符串转储。

于 2013-11-19T14:17:16.333 回答