发送到后端TXT
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-04-24 14:59:03 |
👁️ 阅读: 7
根据浮生梦老师前端课程内容,发送文本到后端可以通过以下方式实现:
## 1. 使用SL:SendLuaNetMsg发送消息到后端
```lua
-- 发送文本消息到后端
SL:SendLuaNetMsg(消息ID, 参数1, 参数2, 参数3, 参数4)
```
示例:
```lua
-- 创建父窗口
local parent = GUI:Win_Create("MessageWindow", 0, 0, 0, 0, false, false, true, false, false, false, 1)
-- 创建输入框
local textField = GUI:TextField_Create(parent, "input_field", 100, 100, 200, 30)
GUI:TextField_setPlaceHolder(textField, "请输入要发送的文本")
-- 创建发送按钮
local sendBtn = GUI:Button_Create(parent, "btn_send", 100, 150, "res/public/1900000612.png")
GUI:Button_setTitleText(sendBtn, "发送到后端")
-- 按钮点击事件
GUI:addOnClickEvent(sendBtn, function()
-- 获取输入框文本
local inputText = GUI:TextField_getString(textField)
if inputText and inputText ~= "" then
-- 发送消息到后端
SL:SendLuaNetMsg(1001, 0, 0, 0, inputText)
SL:Print("已发送文本到后端:", inputText)
else
SL:Print("请输入文本内容")
end
end)
```
## 2. 后端接收处理(服务端脚本)
服务端需要在QFunction-0.lua中注册接收处理:
```lua
-- 服务端接收前端消息
function OnLuaNetMsg(actor, msgID, param1, param2, param3, param4)
SL:Print("收到前端消息:", msgID, param1, param2, param3, param4)
if msgID == 1001 then
-- param1-param3是整数参数
-- param4是字符串参数
local textContent = param4
SL:Print("收到前端文本:", textContent)
-- 可以给前端返回确认消息
sendmsg(actor, 2, "已收到文本:" .. textContent)
end
end
```
## 3. 使用@gm_sendluamsg命令(从服务端到前端)
如果需要从服务端发送文本到前端,可以使用:
```lua
-- 服务端发送
@gm_sendluamsg 消息ID 参数1 参数2 参数3 "文本内容"
```
## 注意事项:
1. `SL:SendLuaNetMsg`是前端发送到后端的函数
2. 消息ID可以自定义,建议使用1000以上的数字避免冲突
3. 参数4支持字符串类型,适合传输文本内容
4. 服务端需要实现`OnLuaNetMsg`函数来接收处理
5. 确保消息ID在前后端保持一致
这样就能实现前后端之间的文本通信了!
← 返回问答库