我有一个 ASP.Net MVC 应用程序,并且使用此代码段从服务器获得了 JSON
响应。
public JsonResult GetVehicleByID(string VehicleID)
{
db.Configuration.ProxyCreationEnabled = false;
var res = from type in db.Vehicles
where type.ID == VehicleID
select new
{
ID = type.ID,
RegNo = type.RegNo
};
return Json(res, JsonRequestBehavior.AllowGet);
}
上面的代码返回以下 Json
(Google Postman)
[
{
"ID": "000001",
"Type": "Internal"
}
]
我使用以下 jQuery Ajax 处理响应
function GetVehicle(id) {
$.ajax({
async: true,
url: "GetVehicleByID?VehicleID=" + id,
cache: false,
dataType: "json",
contentType: "application/json",
success: function (data) {
//Parsing Method 1
//var a = jQuery.parseJSON(data);
//console.log(a.Type);
//Parsing Method 2
var b = $.parseJSON(data);
console.log(b['Type']);
}
});
}
我无法从此响应中提取 Type
元素。 Stack Overflow 上有几个类似的问题,这些问题的解决方案都是关于解析的。我尝试用两种方式解析,但浏览器日志给出以下错误
Uncaught SyntaxError: Unexpected token o in JSON at position 1
非常感谢您提供帮助,而不是将这个问题标记为重复。
最佳答案
尝试一下console.log(data[0].Type)
。我相信 jQuery 已经为您将响应解析为 JSON,因为您指定了 dataType: "json"
并且来自服务器的响应具有正确的 Content-Type
header 。
关于javascript - 如何从 Jquery 中的 Json 响应中提取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38067285/