为什么JS中无法访问此JSON值

时间:2018-04-05 14:21:42

标签: javascript jquery arrays json ajax

请求返回JSON

{
    "get_image_details": [{
        "id": "1",
        "title": "one",
        "image_url": "'http:\/\/salimarts.com\/uploads\/dsc_3100.jpg'",
        "main_category_id": "1",
        "sub_category_id": "2",
        "added_by": "",
        "tags": "",
        "date_of_insert": "2018-04-02 14:15:43",
        "date_of_update": "2018-04-02 14:15:43",
        "main_category_name": "wedding",
        "sub_category1_name": "marwari"
    }]
}

Jquery / Ajax获取JSON

$.ajax({
    url:"<?php echo base_url();?>admin_controllers/PhotoGalleryController/get_image_details",
    type:'POST',
    datatype:'json',
    data:{'image_id':image_id},
    success: function(data)
    {
        var myObj=data;

        var imgTitle = myObj.get_image_details[0]['title'];
        alert(imgTitle);
        console.log(data);

        /*$("#mod").show();*/
        /*$(".modal-content").html(data);*/
    }
});

我在w3schools.com编辑器中尝试了这个JSON,在那里我可以访问但是在localhost上,我遇到了这个错误:

Uncaught TypeError: Cannot read property 'title' of undefined

为什么会发生这种情况请告诉我是否有人面临这类问题

2 个答案:

答案 0 :(得分:1)

Try This ,Its working for me

$.ajax({
    url:"<?php echo base_url();?>admin_controllers/PhotoGalleryController/get_image_details",
    type:'POST',
    datatype:'json',
    data:{'image_id':image_id},
    success: function(data)
    {
        var myObj=data;

        var imgTitle = myObj.get_image_details[0].title;
        alert(imgTitle);
        console.log(data);

        /*$("#mod").show();*/
        /*$(".modal-content").html(data);*/
    }
});

答案 1 :(得分:0)

未捕获的TypeError:无法读取未定义的属性'title'

此错误明确表明您尝试访问其“ title”属性的对象未定义。检查ajax调用是否返回了预期的结果。