jsp使用ajax技术与后台通信

1. 在js文件中;

function createXMLHttpRequest() {
    XMLHttpReq = null;
    if (window.ActiveXObject) {
        XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
        XMLHttpReq = new XMLHttpRequest();
    }
}

function delProjectReport(id) {
    if (window.confirm("确认删除该任务信息吗?")) {
        createXMLHttpRequest();
        var poststr = "id=" + id + "";
        var url = "deleteProjectReport.do?";
        XMLHttpReq.open("post", url, true);
        XMLHttpReq.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded");
        XMLHttpReq.onreadystatechange = delProjectReportCallback;
        XMLHttpReq.send(poststr);
    }
}

function delProjectReportCallback() {
    if (XMLHttpReq.readyState != 4) {
	
    } else {
        if (XMLHttpReq.status == 200) {
            var xmlDOM = XMLHttpReq.responseXML;
            delProjectReports(xmlDOM);
        }
    }
}

function delProjectReports(xmlDOM) {
    var person = xmlDOM.getElementsByTagName("person");
    if (person.length > 0) {
        alert("任务删除成功!");
        window.location.reload(true);
    } else {
        alert("任务删除失败!");
    }
}

2. javaservlet中;

StringBuffer xmlDOM = new StringBuffer();		
xmlDOM.append("<root>");
xmlDOM.append("<persons>");

xmlDOM.append("<person>");
xmlDOM.append("<id>" + id + "</id>");
......
xmlDOM.append("</person>");

xmlDOM.append("</persons>");
xmlDOM.append("</root>");
this.print(request, response, xmlDOM.toString());

private void print(HttpServletRequest request, HttpServletResponse response,String xmlDOM) throws IOException{
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/xml");
    PrintWriter out = response.getWriter();
    out.print(xmlDOM);
    out.close();
}

 3. js文件中;

var person = xmlDOM.getElementsByTagName("person");
for (var i = 0; i < person.length; i++) {
    var id = person[i].getElementsByTagName("id")[0].firstChild.data;
    id = decodeURIComponent(id);
}