我对今天一直试图放在一起的一些jQuery有点麻烦。jQuery插入JSON值到具有特定类的元素
基本上我试图实现的是动态地将价格插入到我的页面上的价格按钮中,通过从JSON订阅源读取。
这个想法是,有一个空的跨度将包含价格。我已经给所有的价格跨越类别.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饲料会是什么样子 - 我已经过滤了一点 /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]。
你必须序列化JSON对象。 看看http://stackoverflow.com/questions/191881/serializing-to-json-in-jquery和http://stackoverflow.com/questions/3593046/jquery-json-to-string – SimaWB 2013-02-20 15:46:06