如何访问AJAX调用返回的JSON值

时间:2015-07-21 21:31:58

标签: php jquery ajax json

我编写了AJAX代码来获取MySQL数据并在HTML页面上显示它。但我的输出没有显示在页面上。

我做错了什么?

PHP:

function nav() {
    $this->dbConnect();
    $qry="SELECT pid, ptitle FROM pages WHERE pagepub='1' ORDER BY porder ASC";
    $result=mysqli_query($this->connect,"$qry") or  die('MySql Error!  ' . mysqli_error());
    $results = array();
    while($row=mysqli_fetch_row($result)) {
        $results[] = $row;
    }
    echo json_encode($results);
    $this->dbclose();       
}

以下是我PHP file的输出:

[
    {
        "pid":"1",
        "ptitle":"One Time Registration Tips"
    },
    {
        "pid":"2",
        "ptitle":"First men in India"
    },
    {
        "pid":"3",
        "ptitle":"First Women in India"
    }
]

JavaScript / HTML:

<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script type="text/javascript" src="dist/js/jquery.js"></script>
<script type="text/javascript">

$(function () {
    jQuery.ajax({
        url: 'http://keralapsctuts.com/app/category.php',
        data: "",
        dataType: 'json', 
        success:function(data) {

            var id = data[0];              //get id
            var title = data[1];           //get name

            $('#output').html(" <a class='list-group-item' href='"+id+"'"+title+" <i class='fa fa-chevron-right pull-right'></i></a>");

        } 
    });
}); 

</script>

2 个答案:

答案 0 :(得分:3)

当您返回更多行时,如果要迭代它们,则应使用for

success:function(data) {
  var result = "";
  for(var i=0; i < data.length; i++) {
    var id = data[i]["pid"];              //get id
    var title = data[i]["ptitle"];        //get name
    result += "<a class='list-group-item' href='"+id+"'>"+title+"<i class='fa fa-chevron-right pull-right'></i></a>";
  }
  $('#output').html(result); //Set output element html
} 

答案 1 :(得分:1)

鉴于您的输出:

[{"pid":"1","ptitle":"One Time Registration Tips"},{"pid":"2","ptitle":"First men in India"},{"pid":"3","ptitle":"First Women in India"}]

您的data可以这样解决:

success:function(data){
    var id = 0;
    var title = "";

    $.each(data, function(k, v){
        id = v.pid;
        title = v.ptitle;
        $('#output').append("<a class='list-group-item' href='"+id+"'>"+title+"<i class='fa fa-chevron-right pull-right'></i></a>");
    });
}