简单的Ajax Jquery的脚本 - 如何获取信息的每一个表中的行吗? [英] Simple Ajax Jquery script- How can I get information for each of the rows in the table?

查看:263
本文介绍了简单的Ajax Jquery的脚本 - 如何获取信息的每一个表中的行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面一个简单的Ajax> PHP> MySQL的例子在这里张贴 http://openenergymonitor.org/右卫门/节点/ 107

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 |
--------------

PHP的code

The php code

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

剧本

$(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); 
      } 
    });
  }); 

行1

如果我把 VAR ID =数据[0]; 我得到的值1。 如果我把 VAR名称=数据[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.

2排ñ3未定义

例如 VAR ID =数据[2]; 返回undefined 等

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

我的问题

  1. 为什么我只能从第一行的值?

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

我怎样才能得到的信息比第一次其他行?

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

从上#1的其他问题我看,我可能要使用whil​​e循环,但我真的不知道为什么或如何。

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.

推荐答案

旧的MySQL扩展的mysql 已经过时,更好地利用的mysqli PDO

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

mysql_fetch_row()能够 只返回1行! 你必须把它变成一个循环,例如:

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 );

您还必须更改JavaScript的:

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 />");
    } 
  } 
});

顺便说一句,我会建议你使用 mysql_fetch_assoc() ,因为它让您的code更灵活和更清洁。

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

这篇关于简单的Ajax Jquery的脚本 - 如何获取信息的每一个表中的行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆