Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

php - Simple Ajax Jquery script- How can I get information for each of the rows in the table?

I'm following a simple ajax>php>mysql example posted here http://openenergymonitor.org/emon/node/107

I can only display information from the first row. My table is set up like so

--------------
|  id  | name|
--------------
| 1    | Pat |
| 2    | Joe |
| 3    | Rob |
--------------

The php code

 $result = mysql_query("SELECT * FROM $tableName");          //query
 $array = mysql_fetch_row($result);                          //fetch result  
 echo json_encode($array);

The script

$(function () 
  {
    $.ajax({                                      
      url: 'api.php', data: "", dataType: 'json',  success: function(data)        
      { 
        var id = data[0];              //get id
        var vname = data[1];           //get name
         $('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); 
      } 
    });
  }); 

ROW 1

If I put the var id = data[0]; I get the value 1. If I put the var name = data[1]; I get Pat.

ROWS 2 n 3 are undefined

Example var id=data[2]; returns undefined etc

My Questions

  1. Why do I only get the values from the first row?

  2. How can I get information for rows other than the first one?

From other questions on Stackoverflow I see that I will probably have to use a while loop, but I'm not really sure why or how.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The old MySQL extension mysql is outdated, better use mysqli or PDO!

mysql_fetch_row() returns only 1 row! You have to put it into a loop, for example:

$data = array();
while ( $row = mysql_fetch_row($result) )
{
  $data[] = $row;
}
echo json_encode( $data );

You also have to change the JavaScript:

$.ajax({                                      
  url: 'api.php', data: "", dataType: 'json',  success: function(rows)        
  {
    for (var i in rows)
    {
      var row = rows[i];          

      var id = row[0];
      var vname = row[1];
      $('#output').append("<b>id: </b>"+id+"<b> name: </b>"+vname)
                  .append("<hr />");
    } 
  } 
});

By the way I would recommend you to use mysql_fetch_assoc() because it makes your code more flexible and cleaner.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...