AJAX没有'不要动态更改我的JSP

AJAX doesn't change my JSP dynamically?

本文关键字:动态 我的 JSP 没有 AJAX      更新时间:2023-09-26

我的AJAX代码出了什么问题?它应该根据条件将按钮的状态更改为启用或禁用。

function loadXML(){
var xmlhttp;
if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}
else
{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            /* alert (xmlhttp.responseText); */
            if(xmlhttp.responseText == true) {
                document.getElementById('scan').disabled=false;
                document.getElementById('secret').value = "true";
            }
            else if(xmlhttp.responseText == false){
                document.getElementById('scan').disabled=true;
                document.getElementById('secret').value = "false";
            }  
        }
}
xmlhttp.open("GET", "ScanJobServlet", true);
xmlhttp.send();
}
setInterval("loadXML()", 5000 );

该函数每5秒执行一次,以检查servlet的响应是否发生了更改。

这是我的Servlet:它有一个事件侦听器,当我插入USB时,响应变为true,如果我拔下USB,则响应变为false。

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    // TODO Auto-generated method stub
    //super.doGet(req, resp);       
    PrintWriter out = resp.getWriter();
    RemovableStorageEventListener listener = new RemovableStorageEventListener() 
    { 
        public void inserted(Storage storage) {
            status = true;
    }
        public void removed(Storage storage) {
            status = false;
        } 
    }; 
    BundleContext bc = AppManager.getInstance().getBundleContext();
    StorageManager sm = StorageManager.getInstance(KSFUtility.getInstance().getApplicationContext(bc));
    sm.addListener(listener);
    if (status==true)
    {
        out.print("true");
    }
    else
    {
        out.print("false");
    }
}

在此代码中,

if (status==true)
  {
    out.print("true");
  }
else
  {
    out.print("false");
  }

您正在返回文字"true""false"。尝试使用不带引号的truefalse。在JavaScript中,"true""false"truefalse不同,因为双引号表示文字。更新:

if (status==true)
  {
    out.print(true);
  }
else
  {
    out.print(false);
  }

在您的javascript代码中,尝试以下操作:

(xmlhttp.responseText == "true")

而不是

(xmlhttp.responseText == true)

(xmlhttp.responseText==false)相同,将其更改为