简体   繁体   中英

How to get the JSON response using same AJAX mechanism

here is the Ajax code i use

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){
}

At the beginning of the page load, i call mainCall() . When i call the same system with XML format this functions works perfectly. But when i call with JSON format, then firstPageData(resJSON) , resJSON becomes null.

any ideas?

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);
            }
        }

This worked !!, I found it in JavaScript: The Definitive Guide: The Definitive Guide

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM