[英]Parse ajax json response
I can't get the data of a JSON object. 我无法获取JSON对象的数据。
This is my API action: 这是我的API动作:
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: 如果我在浏览器中调用API,它将返回:
"{\\"Views\\":396,\\"Likes\\":1,\\"Dislikes\\":0}" “{\\” 视图\\ “:396,\\” 喜欢\\ “:1,\\” 不喜欢\\ “:0}”
However when i call this ajax function: 但是,当我调用此ajax函数时:
$.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 SyntaxError:JSON.parse:JSON数据的第1行第2列出现意外字符
I've used JSON.stringify to convert it to a string and it outputs this: 我使用JSON.stringify将其转换为字符串,并输出以下内容:
{"readyState":4,"responseText":"\\"{\\\\"Views\\\\":396,\\\\"Likes\\\\":1,\\\\"Dislikes\\\\":0}\\"","status":200,"statusText":"OK"} { “readyState的”:4 “responseText的”: “\\”{\\\\ “查看\\\\”:396,\\\\ “喜欢\\\\”:1,\\\\ “不喜欢\\\\”:0} \\ “”,”状态 “:200,” 状态文本 “:” 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:
该请求似乎很好,Chrome开发人员工具将此作为api的答案:
JSON {"Views":396,"Likes":1,"Dislikes":0} JSON {“查看”:396,“喜欢”:1,“不喜欢”:0}
Thanks in advance 提前致谢
Jan 一月
You can only parse strings and data is an object. 您只能解析字符串,并且数据是一个对象。 To get the json as string i just needed to use data.responseText instead.
要获取json作为字符串,我只需要使用data.responseText即可。
$.ajax({
url: '/API/Video/GetVideoInfo/25',
dataType: 'application/json',
complete: function (data) {
var json = JSON.parse(data.responseText);
alert(json["Views"]);
},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.