2014-01-23 129 views
0

更新的網絡請求,我從與network.request功能的網站獲取一些JSON的東西(比特幣的價值)。但是,我希望每當用戶按下更新時,json的東西(比特幣的價值)就會更新到最新版本。這怎麼可能?在Corona SDK

local json = require("json") 
btcPriceText = display.newText("price", 50,100, "Arial", 25) 

local function btcValue(event) 
btcValue = json.decode(event.response) 
dollarbtc= btcValue[1]['rate'] 
end 

local function update() 
if(dollarbtc) then 
    btcPriceText.text = "BTC"..dollarbtc 
end 
end 


network.request("https://bitpay.com/api/rates", "GET", btcValue) 
Runtime:addEventListener("enterFrame", update) 

這是我使用的所有代碼。

+2

你可以發表你的場景和更新按鈕的代碼?你可以把請求放在處理程序中,但是如果沒有看到代碼,很難判斷這是否是最好的方式。 – Schollii

+0

Schollii:我把代碼放在那裏! – user3055331

回答

0

參考出色的Corona docs on buttons頁面,您可以將network.request置於該頁面上第一個示例的handleButtonEvent。這樣,每次用戶點擊按鈕時,都會發出新的請求。一旦響應到達的時候,btcValue函數將被調用,從而設置基於響應的內容dollarbtc值。目前您的update回調在每個時間幀檢查響應數據是否可用。因此,至少在更新文本小部件後,您應該取消設置dollarbtc(將其設置爲零),否則您將在每個時間幀更新小部件!處理響應時更新文本字段:

local function update() 
    if (dollarbtc) then 
     btcPriceText.text = "BTC"..dollarbtc 
     dollarbtc = nil -- do come here again, text field updated! 
    end 
end 

但是,你甚至不需要做

local function btcValue(event) 
    local btcValue = json.decode(event.response) 
    local dollarbtc= btcValue[1]['rate'] 
    btcPriceText.text = "BTC"..dollarbtc 
end 

,你可以對Runtime:addEventListener("enterFrame", update)線,不再需要忘記。

不要忘記添加display.yourButton:addEventListener("tap", handleButtonEvent)使按鍵responds to clicks。輕敲事件沒有階段(而觸摸事件)。