从浏览器中获取HttpRequest对象

var request = null;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
    request = new XMLHttpRequest();
    if (request.overrideMimeType) {
        request.overrideMimeType('text/xml');
    }
} else if (window.ActiveXObject) { // IE
    try {
        request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {alert(ex);}
    }
}

使用HttpRequest返回数据

if(request) {
    request.onreadystatechange = responseHandler;

    var method = "GET";
    var url = "http://localhost:8080/samples/ajaxtest";
    var charset = "UTF-8";
    var params = "";
    try {
        request.open(method, url, true);
        request.setRequestHeader('Cache-Control', 'no-store');
        request.setRequestHeader('Cache-Control', 'no-cache');
        request.setRequestHeader('Pragma', 'no-cache');
        request.setRequestHeader("Content-Type", "application/json; charset=" + charset);
        request.send(params);
    } catch (ex) {
        alert(ex);
    }
}

function responseHandler() {
    var ready = request.readyState;
    if(ready == 4) {
        var status = this.request.status;
        if(status == 200 || status == 0) {
            alert(request.responseText);
            alert(request.responseXML);
        } else {
            //
        }
    }
}

使用服务器返回的JSON数据

function responseHandler() {
    var ready = request.readyState;
    if(ready == 4) {
        var status = this.request.status;
        if(status == 200 || status == 0) {
            var resptxt = request.responseText;
           var func = new Function("return " + resptxt)
           var jsonobj = func();
           alert(jsonobj);
        } else {
            //
        }
    }
}

[ 编辑 | 历史 ]
最近由“jilili”在“2015-12-03 23:37:19”修改