从ajax响应中提取json数据

时间:2016-10-27 06:34:43

标签: javascript jquery json ajax

这是我的js函数

<script>        
function get_class_group(class_id) {

        $.ajax({
            url: '<?php echo base_url();?>index.php?admin/get_class_group/' + class_id ,
            success: function(response)
            {
                var obj = response;
                alert(obj);
            }
        });

    }

</script>

这给我输出

[{"section_id":"13","name":"A","nick_name":"A","class_id":"13","group_id":"4","teacher_id":"6","id":"4","group_name":"Science"}]
[{"section_id":"13","name":"A","nick_name":"A","class_id":"13","group_id":"4","teacher_id":"6","id":"4","group_name":"Science"},
{"section_id":"22","name":"B","nick_name":"b","class_id":"13","group_id":"4","teacher_id":"0","id":"4","group_name":"Science"}]

如果我写alert(obj.section_id);它给了我

  

错误: “未定义”

如何从这个json中获取特定值?

这是我的后端功能:

function get_class_group($class_id) 
    {
        $this->db->select('section.*, class_group.*');
        $this->db->from('section');
        $this->db->join('class_group', 'section.group_id = class_group.id', 'left');
        $this->db->where('section.class_id', $class_id);
        $groups = $this->db->get()->result_array();

        foreach ($groups as $row) {
            $value[] = $row;
            echo json_encode($value);
        }

    }

5 个答案:

答案 0 :(得分:4)

使用每个循环,你的响应是一个对象数组,使用stringify来转换对象中的字符串

$.ajax({
   url: '<?php echo base_url();?>index.php?admin/get_class_group/' + class_id ,
   success: function(response) {
     response = JSON.stringify(response);
     $.each(response,function(i,v){
       console.log(v.section_id);
     });
   }
});

将回声置于foreach函数之外

foreach ($groups as $row) {
            $value[] = $row;

        }
header('Content-Type: application/json');//add the json header if you want to remove the js stringify function 
echo json_encode($value);

答案 1 :(得分:1)

因此,作为响应,您将在json对象中获取多个项目,您必须使用$.each来获取每个项目的值。

//each loop
$.each(obj,function(key,item){
    alert(item.section_id);
});

请查看以下工作片段:

var obj =[{
	"section_id": "13",
	"name": "A",
	"nick_name": "A",
	"class_id": "13",
	"group_id": "4",
	"teacher_id": "6",
	"id": "4",
	"group_name": "Science"
}, {
	"section_id": "22",
	"name": "B",
	"nick_name": "b",
	"class_id": "13",
	"group_id": "4",
	"teacher_id": "0",
	"id": "4",
	"group_name": "Science"
}];

$.each(obj,function(i,v){
    console.log(v.section_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:0)

看起来你的回答是纯粹的字符串。

确保后端在响应中添加Content-Type: application/json标头。

OR:

尝试var res = JSON.parse(response),以便将字符串转换为对象。

答案 3 :(得分:0)

obj是一个数组,所以你得到警告(obj.section_id)为undefined。

使用以下代码获取值

alert(obj[0].section_id); // you will get output as 13
alert(obj[1].section_id); // you will get output as 22

答案 4 :(得分:0)

输出/响应似乎是json数组格式。要从json数组访问任何特定元素,您需要在数组中指定索引位置。

请在下面尝试检查任何特定的元素数据:

警报(OBJ [0] .section_id)

这应警告&quot; section_id&#39;索引0(即,数组中的第一个元素)

您可以随时更改索引以获取特定索引的数据。