我是 Corona 的新手,我正在尝试从 mysql 数据库中提取数据并在应用程序中使用该数据。
数据获取正确,但我可以在函数外访问它。
获取数据的函数:
function loginCallback(event)
if ( event.isError ) then
print( "Network error!")
else
print ( "RESPONSE: " .. event.response )
local data = json.decode(event.response)
if data.result == 200 then
media = data.media_plats
print("Data fetched")
else
print("Something went wrong")
end
end
return true
end
然后我想在这里访问它:
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
elseif phase == "did" then
-- make JSON call to the remote server
local URL = "http://www.mywebsite.com/temp_files/json.php"
network.request( URL, "GET", loginCallback )
print(data.media_plats) -- returns nil
end
end
提前致谢。
最佳答案
您的回调是异步调用的,因此
network.request
将立即返回,并且可能在请求结果返回之前返回。如果您想使用
data.media_plats
(甚至打印),则应在回调内完成/触发。数据在回调中声明为
local
,因此它在函数外不可用。您可以删除local
以使 data 成为全局变量,但这也许就是为什么您有media = data.media_plats
并使用print 在函数外部打印的原因(媒体)
可能就是您想要的。
.
您可以尝试这样的事情作为开始。它发送请求,回调触发现场的一个方法,用新到达的数据更新自己。通常,您会使用一些占位符数据设置 View ,并通过某种进度指示器让用户知道您正在等待数据到达。
免责声明:我不使用 Corona。
-- updates a scene when media arrives
local function updateWithResponse(scene, media)
local sceneGroup = self.view
local phase = event.phase
print(media)
-- display using show after
end
--makes a request for data
function scene:show( event )
if phase == "will" then
elseif phase == "did" then
-- make JSON call to the remote server
local URL = "http://www.mywebsite.com/temp_files/json.php"
network.request( URL, "GET", responseCallback(self))
end
end
-- when media arrives, calls function to update scene.
local function responseCallback(scene)
return function ( event )
if ( event.isError ) then
print( "Network error!" )
elseif ( event.phase == "ended" ) then
local data = json.decode(event.response)
if data.result == 200 then
print("Data fetched")
-- finish setting up view here.
scene:updateWithResponse(data.media_plats)
else
print("Something went wrong")
end
end
end
end
关于android - 电晕函数和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28678577/