簡體   English   中英

在Corona SDK中更新網絡請求

[英]Update a network request in Corona SDK

我正在使用network.request-function從網站上獲取一些json東西(比特幣的價值)。 但是,我希望每次用戶按下update時,該json東西(比特幣的值)都更新為最新版本。 那怎么可能呢?

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 )

這就是我正在使用的所有代碼。

參考按鈕頁面出色的Corona文檔 ,您可以將network.request放在該頁面上第一個示例的handleButtonEvent中。 這樣,每次用戶單擊按鈕時,都會發出一個新請求。 響應到達后,將btcValue調用btcValue函數,從而根據響應的內容設置dollarbtc值。 當前,您的update回調會在每個時間范圍內檢查響應數據是否可用。 因此,至少在更新文本小部件之后,您應該取消設置dollarbtc(將其設置為nil),否則,您將在每個時間段都更新小部件!

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)以便按鈕響應單擊 點擊事件沒有階段(而觸摸事件有階段)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM