每次servlet发生变化时如何执行ajax函数?

时间:2013-07-01 02:16:37

标签: java javascript ajax jsp servlets

我希望在插入USB时启用该按钮,并在移除USB时将其禁用。每次插入或移除USB时,如何使用ajax更改按钮?

的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;
            }
            else {
                document.getElementById('scan').disabled=true;
            } 

        }
}
xmlhttp.open("GET", "ScanJobServlet", true);
xmlhttp.send();
}

Servlet-每次触发事件监听器时如何重新发送对JSP的响应并再次执行ajax函数?

    public static boolean status = 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
    {
        resp.reset();
    }

}

1 个答案:

答案 0 :(得分:0)

您可以设置response.setContentType("application/json"); 并以json字符串创建输出:{"status", "true"}