繁体   English   中英

在 Silverlight 项目中调用异步 JavaScript 代码

[英]Calling async javascript code in a Silverlight project

我们使用 Silverlight 作为我们的 Web 界面解决方案。 我们有一个现有的 Web 服务,但是将跨域和 clientaccesspolicy 文件放入服务器的根目录是我们最后的手段,因此我们首先探索其他选项。 我决定另一种方法是使用 HtmlPage.Window.Invoke() 并使用 javascript 调用 web 服务,接收 JSON 数据,并将其返回到 Silverlight 环境,在那里我将相应地解析它。 我遇到了两个问题:

如果我同步调用它,我的 UI 线程会冻结,直到调用完成并且我不知道如何解决它。 我的印象是 UI 线程是唯一可以访问 javascript 的线程。

如果我异步调用它,我不知道如何在 readyState==4 之前不返回数据。 有任何想法吗?

这是应该适用于大多数最新浏览器的基本XmlHttpRequest解决方案:-

Javascript:-

 function getSomeJSON(url, callback)
 {
     var result = null;
     var xhr = new XmlHttpRequest();
     xhr.open("GET", url, true);
     xhr.onreadystatechanged = function()
     {
          if (xhr.readyState == 4)
          {
              if (xhr.status == 200)
              {
                  result = xhr.responseText;
              }
              xhr = null;
              callback(result);
          }
     }
     xhr.send(null);
 }

在 Sliverlight C# 中

 void FetchData()
 {
     string url = GenerateUrlForService();
     HtmlPage.Window.Invoke("getSomeJSON", new Action<string>(jsonResult =>
     {
         // Code here to handle the json string result.
         // This will run asynchronously so should not block the UI thread 
         // for the duration of the web service call.
     }));

 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM