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

报告相同问题?