我的这个 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 时,响应变为真,如果我拔下 USB,响应变为假。
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");
}
}