function getdata()
local function httpsCB(success, response)
if success then
SL:print(response,'aaa')
return response
end
end
SL:HTTPRequestGet("http://156.232.9.240:199/get.php", httpsCB)
你遇到的异步问题是因为 `SL:HTTPRequestGet` 是异步请求,而你在调用 `getdata()` 时直接使用了它的返回值。这里有几个解决方案:
## 方案1:回调函数(推荐)
```lua
function getdata(callback)
local function httpsCB(success, response)
if success then
SL:Print(response)
if callback then callback(response) end
end
end
SL:HTTPRequestGet("http://156.232.9.240:199/get.php", httpsCB)
end
function npc:sortui()
local ui = self.ui
GUI:setVisible(ui.Panel_1, true) -- 改为正确函数
local list = ui.ListView_1
getdata(function(response)
local datasort = j2t(response) -- 在回调中处理数据
SL:dump(datasort)
-- 这里填充列表
-- for k,v in pairs(datasort) do
-- local p = ui.Panel_3:clone()
-- GUI:ListView_pushBackCustomItem(list, p)
-- end
end)
GUI:addOnClickEvent(ui.close1, function()
GUI:setVisible(ui.Panel_1, false)
end)
end
```
## 方案2:使用事件机制
```lua
-- 定义事件ID
local HTTP_DATA_READY = "HTTP_DATA_READY"
function getdata()
local function httpsCB(success, response)
if success then
SL:Print(response)
-- 派发事件通知数据已准备好
SL:onLUAEvent(HTTP_DATA_READY, response)
end
end
SL:HTTPRequestGet("http://156.232.9.240:199/get.php", httpsCB)
end
function npc:sortui()
local ui = self.ui
GUI:setVisible(ui.Panel_1, true)
local list = ui.ListView_1
-- 先获取数据
getdata()
-- 监听数据准备完成事件
local function onDataReady(eventID, response)
if eventID == HTTP_DATA_READY then
local datasort = j2t(response)
SL:dump(datasort)
-- 处理数据...
end
end
-- 这里需要注册事件监听(具体方式根据你的框架)
-- GUI:addEventListener(HTTP_DATA_READY, onDataReady)
GUI:addOnClickEvent(ui.close1, function()
GUI:setVisible(ui.Panel_1, false)
end)
end
```
## 方案3:状态标记法
```lua
local dataCache = nil
local isDataLoading = false
function getdata(callback)
if dataCache then
if callback then callback(dataCache) end
return
end
if isDataLoading then
-- 可以在这里添加等待队列
return
end
isDataLoading = true
local function httpsCB(success, response)
isDataLoading = false
if success then
dataCache = response
SL:Print(response)
if callback then callback(response) end
end
end
SL:HTTPRequestGet("http://156.232.9.240:199/get.php", httpsCB)
end
```
## 关键点说明:
1. **异步本质**:HTTP请求是异步的,不能直接返回值
2. **回调函数**:最常用的解决方案,在数据准备好后执行后续逻辑
3. **UI更新**:确保在回调中更新UI,避免界面卡死
4. **错误处理**:建议添加失败情况的处理
推荐使用方案1的回调函数方式,这是处理异步请求最直接有效的方法。