日期:2014-05-16  浏览次数:20427 次

在客户端如何实现这个无刷新的需求?
需求是这样的:

我一套winform应用程序,是某个设备操作的应用程序, 现在想通过浏览器方式去操作设备。

目前我的实现方式系统启动时候使用HttpListener创建一个web服务器,让后客户端访问这个服务器加一些url参数,然后我通过这些url参数判断,处理当次的请求,处理完成后返回客户端需要显示的html。
C# code

/// <summary>
        /// 处理web请求
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequst(HttpListenerContext context)
        {
            //得到请求
            if (context.Response != null)
            {
                //得到html
                string strHtml = ControlManager(context);
                //返回客户端的html
                if (!string.IsNullOrEmpty(strHtml))
                {
                    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strHtml);
                    context.Response.ContentLength64 = buffer.Length;
                    context.Response.KeepAlive = false;
                    context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    context.Response.OutputStream.Flush();
                    context.Response.OutputStream.Close();
                }
            }
        }




到这里客户端访问是没有问题,效果也不错。
让我头疼的问题是:
我在设备上面操作了,我改咋样将客户端的页面同步到当前的操作页面呢?
第一种方式: 客户端定时的刷新,一直去请求我在服务器端做处理然后返回客户端需要显示的页面,但是这种刷新一闪一闪的,效果不好。
第二种方式: 使用ajax去实现无刷新效果,但是折腾了半天,貌似不行原因是访问到xmlhttp.responseText就提示xmlhttp没有定义,调试了下提示这个对象还不可以使用,代码如下:
JScript code

function RequestTest() {

                    var xmlHttp;
                    var url = "";

                    if (window.ActiveXObject) {

                                        xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");
                                    }
                                    else if (window.XMLHttpRequest) {
                                        xmlHttp = new XMLHttpRequest();
                                    }
 
                                    xmlHttp.onreadystatechange = function () {
                                        if (xmlhttp.readyState == 4) {
                                            if (xmlhttp.status == 200) {
                                                alert(xmlHttp.responseText);
                                                document.getElementById("myDiv").innerHTML =  xmlhttp.responseText;
                                            }
                                        }
                                    }

                                    xmlHttp.open("GET", url, true);
                                xmlHttp.send();

                }




还有没其他的方法,或者说ajax是我写的不对?还是咋样?求帮助

------解决方案--------------------
//document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
document.getElementById("myDiv").innerHTML = xmlHttp.responseText;
------解决方案--------------------
探讨
//document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
document.getElementById("myDiv").innerHTML = xmlHttp.responseText;