我取一个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