[visual-studio]获取客户端代码工作上 Windows Phone HTML5 应用程序

发布时间: 2014/3/1 5:04:26
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

在 Microsoft Visual Studio 速成我已开始使用"Windows Phone HTML5 应用程序"模板的新项目。如果我运行仿真程序,一切工作正常。下一步我添加以下 JavaScript 到 index.html 页面:

<script type="text/javascript">
   window.onload = function(){

      alert(window.location.href); // -->  x-wmapp0:/Html/index.html

      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange=function()
      {
         alert('ON READY STATE CHANGE');
         if(xmlhttp.readyState==4){
            alert(xmlhttp.responseText);
          }
       }

       //xmlhttp.open("GET","text.txt",true); // I have tried all of these
       //xmlhttp.open("GET","Html/text.txt",true);
       //xmlhttp.open("GET","/Html/text.txt",true);

       xmlhttp.open("GET","x-wmapp0:/Html/text.txt",true);
       xmlhttp.send();
   }

</script> 

现在运行该应用程序在获取窗口的位置,与第一个警报,但得不到任何警报从仿真器中 readyStateonreadystatechange 。Text.txt 文件是作为 index.html 在同一水平上。我有在 IE10 中运行此代码,它只是正常工作。任何关于自己在做什么的想法错了吗?

更新: 已在实际的 Windows 8 手机上部署这并得到相同的结果

欢呼

解决方法 1:

这里是微软告诉我从MSDN

客户端代码仅适用于检索网络资源。即不能使用它来访问的内容从您的应用程序的本地存储,即 XAP 或 IsolatedStorage。

这里是一个示例脚本 + 我都用在过去要变通解决此限制的代码:

JavaScript 的 HTML 页:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
  <title>test</title> 
  <script type="text/javascript">

      function LoadFile(SourceURL) {
          try {
              var httpfreq = new XMLHttpRequest();
              httpfreq.onreadystatechange = function () {
                  filecontent.innerText = "httpfreq.onreadystatechange fired, readyState = " + httpfreq.readyState.toString();
                  if (httpfreq.readyState = 4) {
                      filecontent.innerText = "Status = " + httpfreq.status.toString();
                      if (httpfreq.status = 200) {
                          window.external.notify("Received content" + httpfreq.responseText);
                          filecontent.innerHTML = httpfreq.responseText;
                      }
                      else {
                          window.external.notify("Error loading page: " + SourceURL);
                          filecontent.innerText = "Error loading page " + SourceURL;
                      }
                  }
              };

              httpfreq.open("GET", SourceURL);
              httpfreq.send(null);

          }
          catch (e) {
              if (e.number = 0x80070005) {
                  LoadLocalFile(SourceURL, "GetResourceCallback");
              }
              else {
                  alert(e.name + " " + e.number.toString());
              }
          }
      }

      function LoadLocalFile(SourceURL, callbackfn) {
          window.external.notify("GetResource?file=" + SourceURL + ";callback=" + callbackfn);
      }

      function GetResourceCallback(StringContent) {
          filecontent.innerText = StringContent;
      }


  </script> 
</head> 
<body> 
<p> 
test page: notes.html
</p> 
    <p><input type="button" onclick="LoadFile('text.txt')" value="Load Local" /> </p>
    <p><input type="button" onclick="LoadFile('http://www.somedomain.com/text.txt')" value="Load remote" /> </p>
    <p>---------------------------</p>
    <div id="filecontent"></div>
    <p>---------------------------</p>
</body> 
</html>

和所需的应用程序主机代码 (c#)

private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("Script Notify : {0}",e.Value);

        if (e.Value.Contains("GetResource?file="))
        {
            Dispatcher.BeginInvoke(() =>
                {
                    String szArgs = e.Value;

                    string szResource = null;
                    string szCallbackFn = null;
                    char[] separators = new char[2] {'?',';'};
                    string[] parms = szArgs.Split(separators);

                    for (int i = 1; i < parms.Length; i++ )
                    {
                        if (parms[i].Contains("file="))
                        {
                            szResource = parms[i].Substring(5);
                        }
                        else if (parms[i].Contains("callback="))
                        {
                            szCallbackFn = parms[i].Substring(9);
                        }
                    }

                    if (!String.IsNullOrWhiteSpace(szResource) && !String.IsNullOrWhiteSpace(szCallbackFn))
                    {
                        // read local resource.
                        string szFileContent= "Resource not found!";
                        try
                        {
                            if (String.IsNullOrEmpty(webBrowser1.Base))
                            {
                                // if Base is not set then assume XAP file content.
                                szFileContent = ReadXAPResource(szResource);
                            }
                            else
                            {
                                // else assume IsolatedStorage
                                szFileContent = ReadISOFile(webBrowser1.Base, szResource);
                            }
                        }
                        catch (Exception)
                        {}

                        webBrowser1.InvokeScript(szCallbackFn, szFileContent);
                    }
                });
        }
    }

    private string ReadXAPResource(string szFile)
    {
        string szContent = "File Not Found";
        try
        {
            // in my project HTML files are in the HelpContent folder...
            StringBuilder szPath = new StringBuilder("HelpContent");
            if (!szFile.StartsWith("/"))
                szPath.Append("/");

            szPath.Append(szFile);

            StreamResourceInfo sri = Application.GetResourceStream(new Uri(szPath.ToString(), UriKind.Relative));

            if (null != sri)
            {
                StreamReader strm = new StreamReader(sri.Stream);
                szContent = strm.ReadToEnd();
            }
        }
        catch (Exception) { }

        return szContent;
    }

    private string ReadISOFile(string szBase, string szFile)
    {
        string szContent = "File Not Found";
        try
        {
            string fullPath = szBase + szFile;
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            IsolatedStorageFileStream isfsInput = isf.OpenFile(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            if (null != isfsInput)
            {
                StreamReader strm = new StreamReader(isfsInput);
                szContent = strm.ReadToEnd();
            }
        }
        catch (Exception) { }

        return szContent;
    }
官方微信
官方QQ群
31647020