简体   繁体   English

使用jQuery从JSON获取信息

[英]getting info from json with jquery

Having trouble using ajax to retrieve info from a database. 使用ajax从数据库检索信息时遇到问题。 I was getting the code from here: 我从这里获取代码:

  1. http://openenergymonitor.org/emon/node/107 the code from here worked but would only output 1 item http://openenergymonitor.org/emon/node/107此处的代码有效,但仅输出1个项目
  2. Simple Ajax Jquery script- How can I get information for each of the rows in the table? 简单的Ajax Jquery脚本-如何获取表中每一行的信息? I tried to add this to my code but I could not get it to work. 我试图将其添加到我的代码中,但无法正常工作。

I am getting everything from a table with the following php: 我从具有以下php的表中获取所有内容:

$result = mysql_query("SELECT * FROM voterecords");  

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

which outputs the following if I navigate to that php page: 如果我导航到该php页面,则会输出以下内容:

[["68","1234","0","1234",""],["69","added with ajax","0","this item was added using ajax",""]]

The format of the above is as follows: id, title, votes, description, owner 以上格式如下:ID,标题,投票,描述,所有者

I think that bit all works but I cant be sure because i dont know what JSON is supposed to look like. 我认为这一切都可以,但是我不能确定,因为我不知道JSON应该是什么样子。


Ok now here is the jquery which is supposed to retrieve the info from the JSON and put it into the html element #output 现在,这里是应该从JSON检索信息并将其放入html元素#output的jquery

$(function () 
  {

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

          var id = row[0];              
          var name = row[1];
          var votes = row[2];  
          var info = row[3]; 

          $('#output').append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
                      .append("<hr />");
    } 
  } 
});

I was expecting this to output all the info but nothing happens. 我期望这能输出所有信息,但是什么也没发生。

Your code is fine except you have a missing closing ) from the callback function. 您的代码很好,除非您缺少回调函数的close )

Also, in JavaScript, it's better to place opening braces on the same line, not on the next, as is common in some other languages. 另外,在JavaScript中,最好将开括号放在同一行上,而不是其他某些语言中常见的下一行。

Corrected/cleaned-up code: 更正/清理的代码:

$(function () {
    $.ajax({url: 'retrieve.php', dataType: 'json'}).done(function(rows) {
        for (var i in rows) {
            var row = rows[i];
            var id = row[0];
            var name = row[1];
            var votes = row[2];
            var info = row[3];
            $('#output')
                .append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
                .append("<hr />");
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM