问题
I'm new to JSON and am trying to find a way to query JSON data and bring the info into an appropriate <div>
on my page. I'm using Volusion so the access to the code is limited (it's mostly dynamically generated from server side script) so I'm having to do a couple workarounds. Basically there is a table of products and the only way to get the product code is to grab it out of the URL that's being generated on the anchor tags for those products (each product is set up with a link attached to, for example, /ProductDetails.asp?ProductCode=aroma for the aroma product). I've written Javascript to extract the product code (from the end of the URL) and set it to a variable named productCode.
In my JSON data, I have it set up like this:
[
{
"item": "aroma",
"title": "Aromatherapy Oils",
"price": "$10.00",
},
{
"item": "ah-chairbamboo",
"title": "Modern Bamboo Chair",
"price": "$100.00",
},
{
"item": "hc-mirror",
"title": "Cordless LED Lighting Pivoting Vanity Mirror",
"price": "$45.00",
},
{
"item": "macfrc",
"title": "French Macarons",
"price": "$15.00",
}
]
What if I wanted to just get the title from the JSON sheet where 'aroma' is the item and append that to product container in a div? The way my code is now to get the product code is:
$(".v65-productDisplay a").each(function(){
var productHref = $(this).attr("href");
var productCode = productHref.substring(19,productHref.length);
This works because I have alerted out the productCodes and they are all correct.
I'm wanting this JSON query to obviously be within the each function so it runs on each product on the page. In English, I want to say "where the item value matches the product code in the JSON sheet, I want to print out that title and price" (yes, I understand that's not great English...).
My first failed attempt at querying it (and alerting out the value) is here. This is within:
$(".v65-productDisplay a").each(function(){
var productHref = $(this).attr("href");
var productCode = productHref.substring(19,productHref.length);
$.getJSON("/v/vspfiles/data/productinfo.js", function (data) {
$.each(data, function () {
if (productCode = this['item'])
alert(this['price']);
});
});
});
That did not work though. Sorry if this is confusing, I'm trying to untangle it myself. Thanks so much for any help.
EDIT
Here's a new updated snippet following PSCoder's answer below that's still not working exactly:
$.getJSON("/v/vspfiles/data/productinfo.js", function (data) {
$.each(data, function (i,o) {
if (productCode == o.item)
alert(o.price);
});
});
回答1:
You can do it like this maybe:
$.getJSON("/v/vspfiles/data/productinfo.js", function (data) {
$.each(data, function () {
if (productCode.trim() === this.item)
console.log(this['price']);
});
});
来源:https://stackoverflow.com/questions/16158626/querying-json-data-with-jquery-in-each-function