2015-01-26 75 views
-2

我希望有一個簡單的解決方案,這一個。我只是試圖從我的追加中獲得'net_price',以便在另一個函數中使用。如何訪問變量

任何人都可以幫忙嗎?

JSON

$.getJSON("{{{ url('api/get-price')}}}", { id: $productId }, 
function(data){ 
    if(data.prices == true){ 
     $('#prices span').empty(); 
     $('#prices').fadeIn(2000); 
     $.each(data, function(key, value){ 
      $('.cost').append('<div>Cost: ' + value.net_price +'</div>'); 
     }); 
    } 
}); 

功能,我需要用價格來代替XXXX

var calc = function(currentPrice){ 
    if(currentPrice.getPrice()==100){ 
       this.setOptions({ 
        maxPrice:'XXXXX' 
    }); 
}; 
+3

是'馬上打電話calc'後'GET'打電話?如果沒有,只需將價格存儲在全局變量中。 – tymeJV 2015-01-26 21:16:24

+0

從回調函數調用'calc()'。 – Barmar 2015-01-26 21:21:51

+0

也許你可以告訴我們「數據」的結構是什麼。現在我們只能猜測這裏發生了什麼。另外,目前還不清楚如何調用'calc'函數,currentPrice是什麼等等。 – 2015-01-26 21:23:26

回答

0

你可以做一個全局變量爲淨價,然後更新您的JSON調用中的變量。

// Declare variable globally 
var netPrice = ''; 

$.getJSON("{{{ url('api/get-price')}}}", { id: $productId }, 
function(data){ 

    // Update variable 
    netPrice = value.net_price; 

    if(data.prices == true){ 
     $('#prices span').empty(); 
     $('#prices').fadeIn(2000); 
     $.each(data, function(key, value){ 
      $('.cost').append('<div>Cost: ' + netPrice +'</div>'); 
     }); 
    } 

}); 
0

可能是你可以做

$.each(data, function(key, value){ 
    $('.cost').append('<div>Cost: <span class="netPrice">' + value.net_price +'</span></div>'); 
}); 

calc功能訪問:

var calc = function(currentPrice){ 
    if(currentPrice.getPrice()==100){ // if Saturday 
     this.setOptions({ 
      maxPrice: $('.cost').find('.netPrice').text() 
    }); 
    }; 
} 
+0

我試過這個方法,並且確定它會工作,但是它似乎只在包含撇號的情況下才起作用,作爲串。我如何才能做到最好? – Suba 2015-01-27 20:02:44