簡體   English   中英

電暈函數和變量

[英]Corona functions and variables

我是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. 您的回調是異步調用的,因此network.request將立即返回,並且可能在請求結果返回之前返回。

    如果要使用data.media_plats (甚至打印),則應在回調內部完成/觸發它。

  2. 數據在回調中聲明為local ,因此在函數外部將無法使用。 您可以刪除local變量以使數據成為全局變量,但這也許就是為什么要使用media = data.media_plats ,因此可能需要使用print(media)在函數外部進行print(media)

您可以嘗試使用類似的方法作為開始。 它發送請求,回調函數在場景中觸發一個方法,以使用新到達的數據更新自身。 通常,您將使用一些占位符數據來設置視圖,並讓用戶知道您正在等待數據並帶有某種進度指示器。

免責聲明:我不使用電暈。

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

暫無
暫無

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

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