2011-11-03 91 views
0

我取一個JSON響應,並與響應,我有兩個值:無法訪問頁面範圍內JavaScript變量

  1. 空運成本。
  2. 陸運費用。

我想將這兩個值保存在客戶端的某個位置,這樣當用戶選擇一個單選按鈕或另一個單選按鈕時,我會將該值添加到頁面上的另一個元素。

下面是我在做什麼:

<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":""} 
+0

一個快速解決方法是將'landCost'和'airCost'聲明移到文檔之外,這樣它們將成爲全局的。 – hyperslug

+0

我不明白爲什麼它會在你標記的地方失敗。如果你在'parseJSON'後加上'console.log(data)',你會得到你期望的對象嗎? – hyperslug

回答

0

嘗試

landCost = cityData.LandCost; 
+1

解決了我的問題。 :)雖然好奇,如果我可以像這樣訪問JSON值,爲什麼我需要parseJSON方法? –

+0

我收回來了,我想OP沒有發佈實際的佈局。 @Sergio,如果您調用$ .getJSON,那麼jquery會自動解析它並返回一個可立即使用的對象/數組。 – david

+0

從http://api.jquery.com/jQuery.getJSON/'從jQuery 1.5開始,成功回調函數接收一個「jqXHR」對象,所以我的猜測是parseJSON方法是不必要的 – Kostis

-1

,如果你想在全球範圍內聲明變量,要麼把他們關閉的jQuery($(document).ready(function() {...});)外,或者不使用var聲明它們。如果您不使用var關鍵字,則變量將默認爲全局。

這裏是設置全局變量,不會使用var關鍵字的的jsfiddle:http://jsfiddle.net/jasper/JWtbV/

+0

從不建議人們不要使用'var'。全局是壞的,但是像這樣隱含地創建它們是更糟的一個數量級。 – david

+0

運行一些性能測試後,速度會變慢(這並不令人震驚),但更像是慢了20%,而不是100%或更糟。 – Jasper

+0

從風格的角度來看,我的意思是「更糟糕」,而不是表現。 – david

-1

你有沒有考慮直接使用jQuery的$.data()功能附值到DOM body元素,並從那裏訪問它?

// Set Values 
$('body').data('landCost', data.LandCost); 
$('body').data('airCost', data.AirCost); 

// Retrieve Values // 
console.log($('body').data('landCost'); 
console.log($('body').data('airCost'); 

希望它有幫助。

0

如果您確實必須使用全局變量,則可以將它們直接附加到窗口對象。

window.airCost = cityData.AirCost; 

真的不過你想擁有的JSON請求和「單選按鈕」在同一範圍內處理,讓你不污染全局命名空間可言。

0

您撥打$.parseJSON()的電話將返回null,因爲傳遞給您的回調的數據已被解析爲JSON。

var json = {LandCost:3, AirCost:5}, 
    results = $.parseJSON(json); 

console.log(results); // results == null