传递JSON对象
如果要在Foxtable调用某个JS脚本的函数,而这个函数的参数是JSON类型,或者调用某个元素的方法,而这个方法的参数是JSON类型,那么Foxtable端如何传递JSON参数过去呢?
除了上一节介绍的通过JObject传递,本节再介绍几种方式。
我们以元素的scrollIntoView方法为例,该方法用于滚动元素到可见局域,可以接受一个JSON参数,关于这个函数说明请参考JavaScript的文档。
手动构建JSON字符串
Dim
wv
As
WebViewer = e.Form.Controls("WebViewer1").WebViewer
Dim
js
As
String
=
"document.querySelector('#target1').scrollIntoView({behavior:
'smooth', block: 'center'});"
wv.ExecuteScriptAsync(js)
使用动态类型
Dim
wv
As
WebViewer = e.Form.Controls("WebViewer1").WebViewer
Dim options
=
New
ExpandoObject()
options.behavior =
"smooth"
options.block =
"center"
Dim
jsonOptions = JsonConvert.SerializeObject(options)
'将动态类型序列化成JSON字符串
Dim
js
As
String
=
"document.querySelector('#target1').scrollIntoView("
& jsonOptions &
");"
wv.ExecuteScriptAsync(js)
提醒:
定义动态类型变量的时候,不可以用As指定类型,正确的写法是:
Dim
options
=
New ExpandoObject()
下面这样写是错误的,将无法通过编译:
Dim
options
As
New
ExpandoObject()
使用JObject
Dim
wv
As
WebViewer = e.Form.Controls("WebViewer1").WebViewer
Dim
options
As
New
JObject()
options("behavior")
=
"smooth"
options("block")
=
"center"
Dim
jsonOptions = options.ToString()
'将JObject对象转成JSON字符串
Dim
js
As
String
=
"document.querySelector('#target1').scrollIntoView("
& jsonOptions &
");"
wv.ExecuteScriptAsync(js)
使用匿名类型
'''Async
Dim
wv
As
WebViewer = e.Form.Controls("WebViewer1").WebViewer
Dim
options
As
String
=
New
With
{.behavior =
"smooth",.block
=
"center"}
Dim
jsonOptions
As
String
= JsonConvert.SerializeObject(options)
'将匿名类型序列化成JSON字符串
Dim
js
As
String
=
"document.querySelector('#target1').scrollIntoView("
& jsonOptions &
");"
Await
wv.ExecuteScriptAsync(js)
使用字典
Dim
wv
As
WebViewer = e.Form.Controls("WebViewer1").WebViewer
Dim
options
As
New
Dictionary(Of
String,
Object)
options.Add("behavior",
"smooth")
options.Add("block",
"center")
Dim
jsonOptions = JsonConvert.SerializeObject(options)
'将字典序列化成JSON字符串
Dim
js
As
String
=
"document.querySelector('#target1').scrollIntoView("
& jsonOptions &
");"
wv.ExecuteScriptAsync(js)
以上五段代码实现的功能完全一样,一般来说,简单的手动构建JSON字符串即可,如果比较复杂的数据,推荐用动态类型(ExpandoObject)构建,但因为历史原因(JObject最先出现),所以本文档用JObject较多。