我今天尝试组合的一些 jQuery 遇到了一些问题。
基本上,我想要实现的是通过读取 JSON feed 将价格动态插入到我页面上的价格按钮中。
这个想法是有一个空的范围来包含价格。我已经给出了 .getPriceNew
类中的所有价格。每个范围还有一个 id,它等于该商品的 SKU 编号,如 <span class="getPriceNew" id="123456"></span>
。
其机制是,对于具有类 .getPriceNew
的每个范围,将查询 JSON 以获取信息,并将 SKU ID 用作查询字符串的一部分。
这是我尝试过的代码示例
jQuery
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
HTML
<span class="getPriceNew" id="123456"></span>
<span class="getPriceNew" id="789123"></span>
<span class="getPriceNew" id="456789"></span>
<span class="getPriceNew" id="654321"></span>
JSON 示例 这就是 JSON feed 中的单个项目的样子 - 我已经对其进行了一些过滤 /api/MyApi.svc/GetProductBySku/123456
已使用有效的 JSON 进行更新
{
"Age": {
"Description": "Age 18+",
"Thumbnail": "http://someurl.com/productImages/assets/img//icon18.gif"
},
"Barcode": {
"Barcode": "5026555408684"
},
"Description": "HTML",
"Id": 12214,
"Packshots": [
"http://someurl.com/productImages/914383/1min.jpg",
"http://someurl.com/productImages/914383/2med.jpg",
"http://someurl.com/productImages/914383/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "Format",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Product Title",
"Variants": [
{
"Id": 22488,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 49.97,
"Sku": 914383,
"Type": {
"Description": "Pre-Order"
}
}
],
"Vendor": {
"Description": "Take Two Interactive Software"
},
"VideoHTML": "HTML",
"status": {
"Response": "product found",
"Success": true
}
}
我希望得到一些帮助,因为我在这个阶段真的很摸不着我的新手头。我已经设法让 console.log 将价格输出到日志中,但是当我尝试将它们插入到跨度中时,我得到的只是 [object] [Object]。
最佳答案
你在做什么
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
getJSON
返回一个 jqXHR
对象,这不是您需要的。试试这个:
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
// Save a refference to this span.
var thisSpan = $(this);
$.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
// Request complete, NOW we can use the data we got!
thisSpan.html("€"+data.Variants[0].Price);
});
})
回调是您想要使用从 AJAX 调用获取的数据的地方。所有 AJAX 方法($.ajax、$.get、$.post、$.getJSON 等)都将返回 jqXHR对象。
关于javascript - jQuery 将 JSON 值插入到具有特定类的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14983886/