0

这是我使用的 Ajax 代码

function AJAXInteraction(url, callback) {
    var req = init();
    req.onreadystatechange = processRequest;

    function init() {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
    }

    function processRequest () {
        // readyState of 4 signifies request is complete
        if (req.readyState == 4) {
            // status of 200 signifies sucessful HTTP call
            if (req.status == 200) {
                if (callback) callback(req.responseXML);
            }
        }
    }

    this.doGet = function() {
    req.open("GET", url, true);
    req.send(null);
        }
    }

function mainCall(){
    var req_url = "requestItems.php?format=json&num=100"
    var ajax = new AJAXInteraction(req_url, firstPageData);
    ajax.doGet();   
}

function firstPageData(resJSON){
}

在页面加载开始时,我调用mainCall(). 当我用 XML 格式调用相同的系统时,此功能可以完美运行。但是当我用 JSON 格式调用时,则firstPageData(resJSON)变为resJSONnull。

有任何想法吗?

4

1 回答 1

1
function processRequest () {
        // readyState of 4 signifies request is complete
        if (req.readyState == 4) {
            // status of 200 signifies sucessful HTTP call
            if (req.status == 200) {
                var type = req.getResponseHeader("Content-Type");
                if (type.indexOf("xml") !== -1 && req.responseXML)
                    callback(req.responseXML);
                else if (type=== "application/json")
                    callback(JSON.parse(req.responseText));
                else
                    callback(req.responseText);
                //if (callback) callback(req.responseXML);
            }
        }

这行得通!!,我在JavaScript: The Definitive Guide: The Definitive Guide中找到了它

于 2012-09-06T20:20:58.227 回答