繁体   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