传递JSON对象

本示例可参考示例文件"CaseStudy\WebViewer\调用Foxtable对象.Table"的窗口"传递JSON对象"。

前端调用Foxtable的自定义函数,经常需要传递比较复杂的数据。

复杂数据传递最好的方式是通过JSON对象。

示例

1、首先增加一个自定义函数ProcessEmployee,代码为:

Dim jsonStr As String = Args(0)
Dim
emp As JObject = JsonConvert.DeserializeObject(jsonStr) '收到的是字符串,要先解析成JSON对象
' 提取数据
Dim
name As String = emp("name").ToString()
Dim
monthSalary As Double = CDbl(emp("monthSalary"))
'
计算年薪
Dim
yearSalary As Double = monthSalary * 12
'
返回JSON
Dim
result As New JObject
result(
"name") = name
result(
"yearSalary") = yearSalary
result(
"message") = CExp("你好,{0},年薪{1}", name, yearSalary)
Return
result.ToString() 'JSON对象必须以字符串形式返回给前端,切记

这个函数会收到前端传递的一个表示员工信息的JSON对象(字符串形式),进行简单的处理后(计算年薪),然后以JSON字符串的形式返回给前端

2、窗口的AfterLoad事件代码:

'''Async
Dim wv As WebViewer = e.Form.Controls("WebViewer1").WebViewer
Await
wv.EnsureCoreWebView2Async(Nothing)
Dim
ft As New FoxLib(wv)
wv.CoreWebView2.AddHostObjectToScript(
"ft", ft)
 

'
测试页面
Dim
html As String = <![CDATA[
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>JSON
传递演示</title>
</head>
<body>
    <h2>JSON
数据传递演示</h2>
    <p>
点击按钮发送JSONFoxtable,接收返回的JSON</p>   
    <button onclick="testJson()">
测试JSON传递</button>   
    <div id="result" style="margin-top:20px; padding:10px; background:#f0f0f0;"></div> 
    <script>
        const ft = window.chrome.webview.hostObjects.sync.ft;       
        function testJson() {
            //
构建要发送的JSON对象
            const emp = {
                name: "
张三",
                age: 30,
                title: "
工程师",
                monthSalary: 8500.50
            };           

            // 一行代码:发送JSON,接收JSON
            const result = ft.Functions.Execute("ProcessEmployee", JSON.stringify(emp));
            //
收到的是字符串,如果要使用JSON对象,还需要解析:
            const resultObj = JSON.parse(result);           

            // 显示结果
            document.getElementById('result').innerHTML =
                '
发送的是对象: ' + JSON.stringify(emp) + '<br><br>' +
                '
接收的是字符串: ' + result + '<br><br>' +
                '
解析成对象使用: ' + '"name":' + resultObj.name +  ',"yearSalary":' + resultObj.yearSalary;
        }
    </script>
</body>
</html>
]]>
.Value
wv.NavigateToString(html)

提示:

Foxtable和前端都不能直接传递JSON对象,传递的都是JSON字符串,所以两边收到数据后都要先进行解析才可以使用。


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