weixin_33725272 2018-12-14 15:03 采纳率: 0%
浏览 40

解析ajax json响应

I can't get the data of a JSON object.

This is my API action:

    public string GetVideoInfo(uint videoID)
    {
        ApiVideoInfo videoInfo = new ApiVideoInfo()
        {
            Likes = BitVidDb.GetLikes(videoID),
            Dislikes = BitVidDb.GetDislikes(videoID),
            Views = BitVidDb.GetViews(videoID),
        };

        return JsonConvert.SerializeObject(videoInfo);
    }

If i call the API in the browser it returns:

"{\"Views\":396,\"Likes\":1,\"Dislikes\":0}"

However when i call this ajax function:

    $.ajax({
        url: '/API/Video/GetVideoInfo/25',
        dataType: 'application/json',
        complete: function (data) {
            var json = JSON.parse(data);
            alert(json["Views"]);
        },
    });

It gives me the following error:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

I've used JSON.stringify to convert it to a string and it outputs this:

{"readyState":4,"responseText":"\"{\\"Views\\":396,\\"Likes\\":1,\\"Dislikes\\":0}\"","status":200,"statusText":"OK"}

Is there some additional step i need to take to get the values? The request seems to be fine Chrome dev tools gives this as the answer to the api:

JSON {"Views":396,"Likes":1,"Dislikes":0}

Thanks in advance

Jan

  • 写回答

1条回答 默认 最新

  • weixin_33705053 2018-12-14 17:58
    关注

    You can only parse strings and data is an object. To get the json as string i just needed to use data.responseText instead.

    $.ajax({
        url: '/API/Video/GetVideoInfo/25',
        dataType: 'application/json',
        complete: function (data) {
            var json = JSON.parse(data.responseText);
            alert(json["Views"]);
        },
    });
    
    评论

报告相同问题?