dongwu1410 2013-01-18 15:51
浏览 29
已采纳

如何使用php和mysql数组获取json对象

I am trying to get json data from php and when by using jquery json it show me undefined object. I don't know where is problem in my code. can any one help ?

Here is json code :

$("document").ready(function() {
$("body").css("background", "#ccc");
$(".sitebuttons").click(function() {
    $("#subcat").html("");
    $.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
        $.each(data, function(index, array) {
            $("#subcat").append("<input type='button' class='subcat' id='" + data.subcat_id + "' value='"
                    + data.subcat_name + "'></p>");
        });
    });
});

});

and Here is PHP Code

 $select_subcat = mysql_query("SELECT * FROM wp_leadsubcat WHERE cat_id=" . $_GET['catid']);
$rows = array();
while ($result2 = mysql_fetch_assoc($select_subcat)) {
    $rows[] = $result2;
}
echo json_encode($rows);

Please check screenshot here : http://imageshack.us/photo/my-images/560/screenshotqvl.png/

  • 写回答

2条回答 默认 最新

  • downing1988 2013-01-18 16:37
    关注

    read documentation about jquery each.

    in short jQuery.each( collection, callback(indexInArray, valueOfElement) )

    index means index and valueOfElement means the current element from the collection. In your case row.

    here is a fix.

    $("document").ready(function() {
    $("body").css("background", "#ccc");
    $(".sitebuttons").click(function() {
      $("#subcat").html("");
      $.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
        $.each(data, function(index, row) {
          $("#subcat").append(
             "<input type='button' class='subcat' id='" + row.subcat_id + "' value='"+ row.subcat_name + "'>"
          );
        });
      });
    });
    

    and the append part could be optimized like this (it's more readable as you can see)

    $("#subcat").append($(
      "<input/>"
    , {
        cssClass: 'subcat'
      , id: row.subcat_id
      , value: row.subcat_name
    }
    ));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 深度学习残差模块模型
  • ¥20 两个不同Subnet的点对点连接
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)