电晕功能和变量

时间:2015-02-23 16:35:26

标签: android ios mysql lua 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

提前致谢。

1 个答案:

答案 0 :(得分:1)

  1. 您的回调是异步调用的,因此network.request将立即返回,并且可能在请求结果返回之前返回。

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

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

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

    免责声明:我不使用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