2015-02-23 59 views
0

即时通讯和即时通讯试图从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 

在此先感谢。

回答

1
  1. 回调是异步调用,从而network.request将立即和可能回来请求结果之前有回来。

    如果你想使用data.media_plats(即使是打印),它应该在回调中完成/触发。

  2. 数据在回调中声明为local,所以它不会在函数外部可用。您可以删除local以使数据成为全局变量,但也许这就是您拥有media = data.media_plats的原因,因此使用print(media)以外的功能打印可能是您想要的。

你可以尝试这样的事情作为开始。它发送请求并且回调在场景中触发一个方法用新到达的数据更新自己。通常你可以用一些占位符数据设置视图,并让用户知道你在等待数据到达某种进度指示器。

声明:我不使用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 
+0

感谢您的快速响应。正如所说的即将来临的电晕,你能否在第一步中解释我应该做些什么?是的,这正是为什么媒体变量在那里,但即使我从数据删除本地电子邮件无法打印到媒体... – 2015-02-23 17:29:08

+0

@TyTeam看到编辑的代码。希望能帮助到你。 – ryanpattison 2015-02-23 17:52:15

+0

你的代码完美工作。非常感谢你的帮助:D – 2015-02-23 18:07:12