Reputation: 7279
I need to load in some prices from a file (the server doesn't have a database set up):
PriceChicken:2.16
PriceRibs:1.84
PriceBrisket:14.00
PricePulledPork:12.00
PriceSides:5.00
The javascript block like this:
var price = {
"PriceChicken": "1",
"PriceRibs": "1",
"PriceBrisket": "1",
"PricePulledPork": "1",
"PriceSides": "1"
};
function loadVars(){
console.log(price["PriceChicken"]);
$.get("price.txt", function(data){
dataarray = data.split("\n");
for(i = 0;i < dataarray.length; i++){
var line = dataarray[i].split(":");
console.log(price[line[0]]);
price[line[0]] = line[1];
console.log(price[line[0]]);
}
});
console.log(price["PriceChicken"]);
}
loadVars();
Unfortunately the function inside of the $.get part can't seem to see the global price variable.
So for the first item it shows: 1, undeclared, 2.16, and then 1 again when it leaves the $.get function.
Is there a better way to get the global variable to work, or a better way to pull this information in?
Edit: I was stupid and didn't check all my vars. As my penance I'm going to do it the right way and learn to use JSON.
Upvotes: 0
Views: 129
Reputation: 207501
The $.get
call is asynchronous. You are treating it as a synchronous call.
The line console.log(price["PriceChicken"]);
is called before the file is processed.
Better to use JSON format.
prices.json
{
"PriceChicken" : 2.16,
"PriceRibs" : 1.84,
"PriceBrisket" : 14.00,
"PricePulledPork" : 12.00,
"PriceSides" : 5.00
}
JavaScript
var price = {};
$.getJSON("prices.json", function(data){
$.extend(price,data);
});
Upvotes: 3
Reputation: 2533
var price = {
"PriceChicken": "1",
"PriceRibs": "1",
"PriceBrisket": "1",
"PricePulledPork": "1",
"PriceSides": "1"
};
function set_price(key, value){
price[key] = value;
};
function loadVars(){
console.log(price["PriceChicken"]);
$.get("price.txt", function(data){
dataarray = data.split("\n");
for(i = 0;i < dataarray.length; i++){
var line = dataarray[i].split(":");
// set price
set_price(line[0], line[1]);
console.log(price[line[0]]);
}
});
console.log(price["PriceChicken"]);
}
loadVars();
Upvotes: 0