我取一個JSON響應,並與響應,我有兩個值:無法訪問頁面範圍內JavaScript變量
- 空運成本。
- 陸運費用。
我想將這兩個值保存在客戶端的某個位置,這樣當用戶選擇一個單選按鈕或另一個單選按鈕時,我會將該值添加到頁面上的另一個元素。
下面是我在做什麼:
<script type="text/javascript">
$(document).ready(function() {
var landCost;
var airCost;
$("#ddlCiudad").change(function() {
var idCity = $("#ddlCiudad").val();
$.getJSON("/ProductCheckout/GetPriceForLocation", { cityId: idCity, productId: idProduct, type: "land" },
function (cityData) {
console.log("Recieved json data."); //This part works. It outputs.
var data = $.parseJSON(cityData);
console.log("Parse JSON response."); //This part works. It outputs.
landCost = data.LandCost;
console.log("Assigned value of LandCost"); //FAILS HERE. nothing is shown. not even an error.
airCost = data.AirCost;
console.log("Assigned value of AirCost");
alert(landCost);
console.log("Alerted land!");
alert(airCost);
console.log("Alerted air!");
}
);
});
所以,你有什麼建議?如果我在change()事件中聲明變量,則需要具有此JSON響應的值,可用於該頁面,否則它將超出範圍。
{"DaysToShip":" TER = 48 Hrs/AER = 24 Hrs","LandCost":"25,00","AirCost":""}
一個快速解決方法是將'landCost'和'airCost'聲明移到文檔之外,這樣它們將成爲全局的。 – hyperslug
我不明白爲什麼它會在你標記的地方失敗。如果你在'parseJSON'後加上'console.log(data)',你會得到你期望的對象嗎? – hyperslug