访问JSON值是未定义的 - jQuery Ajax

时间:2014-11-12 16:36:40

标签: jquery ajax json

我已经有一段时间了,因为我使用过jQuery,而且我很难从服务器返回的JSON中获取值。

C#方法

        [HttpGet]
        public JsonResult AjaxGetSingleNewsItem(int Id)
        {
            string json = JsonConvert.SerializeObject(news.GetNewsItems().Where(d => d.UniqueId == Id), formatting: Formatting.Indented);
            var v = JArray.Parse(json);

            var model = (from p in v
                         select new ModelNewsWidget()
                         {
                             Id = p["UniqueId"].ToString(),
                             ImagePath = _imagePath,
                             NewsItemImageReference = p["NewsItemImageReference"].ToString(),
                             Title = p["Title"].ToString().Substring(0, 14),
                             SubTitle = p["Title"].ToString().Substring(15),
                             AddedOn = Convert.ToDateTime(p["AddedOn"].ToString()).ToShortDateString(),
                             NewsRef = p["BodyText"].ToString().Substring(5, 13),
                             BodyText = p["BodyText"].ToString().Replace(System.Environment.NewLine, string.Empty)
                         }).ToList();

            json = JsonConvert.SerializeObject(model);

            return new JsonResult()
            {
                Data = json,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                MaxJsonLength = Int32.MaxValue
            };
        }

function getSingleNewsItem(id) {
        var url = '@Url.Action("AjaxGetSingleNewsItem", "News")';
        var data = {
            id: id
        };

        $.ajax({
                type: "GET",
                url: url,
                data: data,
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                success: function (data) {
                    alert(data[0].NewsRef);
                },
                error: function (data) {
                }
            });
        };

这是未定义的:

alert(data[0].NewsRef);

这是我的JSON

[
    {
        "ImagePath": "http://vmwebapps.rhs.net/AMT/AMT_Files/HortifactsAttachmentsTest/NewsItems/",
        "Id": "6",
        "NewsItemImageReference": "http://vmwebapps.rhs.net/AMT/AMT_Files/HortifactsAttachmentsTest/NewsItems/9750cf57-bc14-4205-9e6c-83c8406f3f82.jpg",
        "Title": "Tree fungus ID",
        "SubTitle": " Inonotus dryadeus",
        "AddedOn": "16/09/2013",
        "NewsRef": "204201/252874",
        "BodyText": "Ref: 204201/252874The fruiting bodies are those of a fungus called Inonotus dryadeus. Oak is the most common host of this fungus, which can often cause decay of the inner parts of the root system and the base of the trunk.Whilst the fungus can cause extensive decay, the effect on the tree itself can be very variable. Some trees will survive for many years or even indefinitely - although the central roots and wood may decay the hollow tree remains alive and standing on 'stilts' of buttress roots. However, if the decay also affects these roots then there is a risk of the tree falling. In a case such as this we would always recommend having the tree examined in situ by an arboricultural consultant, particularly if there is any risk of injury or damage to property should the tree fall. The consultant will be able to check the location and extent of the decay, and recommend any appropriate remedial action (such as crown reduction).The link below takes you to our web profile on bracket fungi. This does not mention Inonotus dryadeus specifically, but gives the contact details for the Arboricultural Association who will be able to provide you with a list of suitably-qualified consultants operating in your area. http://apps.rhs.org.uk/advicesearch/Profile.aspx?pid=98I hope this information is helpful.Yours sincerely, John ScracePlant Pathologist"
    }
]

萤火虫的结果:

console.log(data);
console.log(data.NewsRef);
console.log(data[0].NewsRef);

[{"ImagePath":"http://vmwebapps.rhs.net/AMT/AMT_Files/HortifactsAttachmentsTest/NewsItems/","Id":"12","NewsItemImageReference":"http://vmwebapps.rhs.net/AMT/AMT_Files/HortifactsAttachmentsTest/NewsItems/7bc9ca37-d3da-4972-9f19-be3f245eb905.jpg","Title":"Large Yellow U","SubTitle":"derwing","AddedOn":"25/09/2013","NewsRef":" yellow under","BodyText":"Large yellow underwing - sent via twitter - Anna says several already submitted to our entomologists this week: https://twitter.com/HannahBellaaaa/status/382814806886973440/photo/1Massed eggs diagnostic: http://ukmoths.org.uk/show.php?bf=2107"}] (index):471

undefined (index):472
undefined 

我已经用头撞了一下墙,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

您需要先解析JSON数据,然后才能访问它。

尝试以下方法:

success: function(data){ 
var parsedData =  $.parseJSON(data);
alert(parsedData[0].NewsRef);
}