我的这段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”
。尝试使用不带引号的 true
和 false
。
在 JavaScript 中,"true"
和 "false"
与 true
和 false
不同,因为双引号表示文字。更新:
if (status==true)
{
out.print(true);
}
else
{
out.print(false);
}
关于java - AJAX 不会动态更改我的 JSP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17416041/