JSON消息

本节示例可以参考示例文件"CaseStudy\WebViewer\接收消息.Table"的窗口"JSON消息"。

本示例的任务是演示如何在前端页面向Foxtable发送JSON消息。

1、窗口的AfterLoad事件代码:

'''Async
Dim wv As WebViewer = e.Form.Controls("WebViewer1").WebViewer
Await
wv.EnsureCoreWebView2Async(Nothing) '初始化浏览器
'
定义测试页面
Dim
html As String = <![CDATA[
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>JSON
数据通信</title>
</head>
<body>
    <h3>
发送JSON格式用户信息</h3>
    <button onclick="sendUserInfo()">
发送用户信息</button>
    <script>
        function sendUserInfo() {
            //
定义JSON对象
            const user = {
                Name: "
张三",
                Age: 25,
                IsVIP: true
            };
            //
发送对象(会自动序列化为JSON字符串)
            chrome.webview.postMessage(user);
        }
    </script>
</body>
</html>
]]>
.Value
wv.CoreWebView2.NavigateToString(html)
'打开测试页面

2、WebMessageReceived事件代码:

Dim user As JObject = JsonConvert.DeserializeObject(e.WebMessageAsJson)
Dim
name As String = user("Name")
Dim
age As Integer = user("Age")
Dim
isVip As Boolean = user("IsVIP")
Dim
info As String = "姓名:" & name & vbCrLf & "年龄:" & age & vbCrLf & "VIP:" & isVip
MessageBox.Show(
"收到前端发来的消息:" & vbCrLf & info,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information)

也可以不用解析为JObject,用ExpandoObject,代码如下:

Dim user As Object = JsonConvert.DeserializeObject(Of ExpandoObject)(e.WebMessageAsJson)
Dim
name As String = user.Name
Dim
age As Integer = user.Age
Dim
isVip As Boolean = user.IsVIP
Dim
info As String = "姓名:" & name & vbCrLf & "年龄:" & age & vbCrLf & "VIP:" & isVip
MessageBox.Show(
"收到前端发来的消息:" & vbCrLf & info,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information)

我个人更喜欢用ExpandoObject,因为用原点符号访问数据更方便。


本页地址:http://www.foxtable.com/webhelp/topics/6227.htm