【发布时间】:2018-09-22 09:23:38
【问题描述】:
我正在使用 ASP.Net Web API v2 从数据库中检索产品列表。使用这个 web api,我获得了一个 JSON,其中包含我的视图数据并使用 jquery 显示它。但是,在获取 JSON 后,将从 Price 属性中删除有效数字。
例如-
<ArrayOfProductModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/ProductManagement.Models">
<ProductModel>
<Description>
Get ready to channel your inner dark knight with this epic Batman tee!
</Description>
<Id>1</Id>
<Imagepath>/Images/559276_1.jpg</Imagepath>
<Name>Batman T-Shirt (Men's)</Name>
<Price>996.0000</Price>
</ProductModel>
这是来自 API 的 XML。还有我的 Jquery 代码:
var uri = '/api/Product';
$(document).ready(function () {
$.getJSON(uri).done(function (data) {
$.each(data, function (key, item) {
console.log(item.Price);
var img='<img src='+item.Imagepath+' alt="productImage" height="150px" width="150px">'
var $tr=$('<tr>').append(
$('<td>').text(item.Id),
$('<td>').text(item.Name),
$('<td>').text(item.Description),
$('<td>').html(img),
$('<td>').text(item.Price),
);
$('#productlist').append($tr);
});
});
});
现在 console.log 和带有 item.Price 的 td 标记都显示 996 而不是 996.0000。有什么办法可以防止有效数字被删除?
【问题讨论】:
-
你的“JSON”在我看来有点像 XML...
-
Web api 不是同时返回 XML 和 JSON 吗?我提到这就是 XML ......我无法在访问 /api/Products 时强制它返回 JSON
-
你是对的,只是奇怪的是,你正在请求获取 JSON,但在你将响应格式化为 XML 的问题中。我想知道它实际上是如何工作而没有抛出任何错误:)
-
解决问题试试
item.Price.toFixed(2) -
谢谢,Rory,我想我可以使用 item.Price.toFixed(4) 来解决这个问题。不知道为什么默认情况下会从 JSON 中删除有效数字,知道为什么吗?
标签: javascript jquery json asp.net-web-api