解码jQuery中的JSON对象 [英] Decode JSON object in jquery

查看:115
本文介绍了解码jQuery中的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用以下代码通过php将数据编码为json格式

I have encoded data in json format by php using the following code

  <?php

    $response = array();

    while ($row = mysql_fetch_array($result)) {

            $user["id"]                 = $row["id"];
            $user["name"]               = ucfirst($row["user_name"]);
            $user["date"]               = $row["date_of_treatment"];
            $user["age"]                = $row["age_of_user"];

            // push single user into final response array
            array_push($response, $user);

            $count = $count+1;
            $sum_of_age = $sum_of_age+$row["age_of_user"];

        }

    $response["average_age"]  = $sum_of_age / $count;
    $response["count"] = $count;

    echo json_encode($response);

?>

我必须在 jquery 中解码此json 为此,我已经使用了这种方法

I have to decode this json in jquery for that the i have used this method

success: function(result){  

      if(result.length > 0) {      
          for(var i=0; i < result.length; i++) {
            obj = result[i];

            output = output + "<tr><td>"+(i+1)+"</td><td>"+obj.name+"</td><td>"+obj.age+"</td><td>"+obj.date+"</td><tr>";
          } 
          output = output+"<tr><td colspan='2' style='text-align:center'>"+obj.average_age+"</td></tr>"
        } else {
          output = output + "<tr><td colspan='4' style='text-align:center'>No Records Found..!</td></tr>";
        }
         $("#search-list tbody").html(output);     
      }  
  });

但是这不起作用.请帮助我纠正这个错误

but this is not working. please help me to get this correct

结果以这种格式进入控制台.如何遍历这个?.

result is getting in console in this format. how to iterate through this ?.

{"0":{"id":"35","name":"Ahamed shajeer","date":"2014-03-03","age":"25"},"1":{"id":"36","name":"Meshajeer","date":"0000-00-00","age":"25"},"2":{"id":"37","name":"Iam shajeer","date":"0000-00-00","age":"25"},"average_age":25,"count":3}

推荐答案

尝试一下

success: function(data) {
    var output = "";
    if (data.length > 0) {
        $.each(data, function(index, item) {
            output += "<tr><td>" + (i + 1) + "</td><td>" + item.name + "</td><td>" + item.age + "</td><td>" + item.date + "</td><tr>";
            output += "<tr><td colspan='2' style='text-align:center'>" + item.average_age + "</td></tr>";
        });
    } else {
        output += "<tr><td colspan='4' style='text-align:center'>No Records Found..!</td></tr>";
    }
    $('#search-list tbody').html(output);
}

这篇关于解码jQuery中的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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