我如何让AJAX为我工作?

时间:2017-12-16 14:11:07

标签: javascript ajax

我一直在制作API,而我正在开发一个叫做Swerer的API。 Swerer是一种使用AJAX的简单有效的方法。现在的问题是,当我使用Swerer.getFile("file.txt")时,它返回undefined而不是内容。任何帮助将不胜感激。

 /*
        Complex.js 1.0.0
        Dec 14, 2017
    */

    (function(){

    if(!document){
            throw new Error("Complex.js needs a window with a document");
        }
    })();

    var toString = Object.prototype.toString;
    // Make X
    X = function(){

    };
    X.extend = function(){
        var target = arguments[0], obj, arg = arguments;
        for (var i = 0; i < arg.length; i++) {
            if(toString.call(arg[i]) == "[object Boolean]"){
                if(arg[i] !== false){
                    if(!target){
                        obj = [];
                    }else{
                        for(i in target){
                            target[i] = obj[i];
                        }
                    }
                }else{
                    obj = [];
                }
            }
        }
        return obj;
    };
    // Make constructors
    X.extend({
        // We are going to make something called Swerer
        Swerer: function(){
            X.call(this);
        },
        isFunction: function(obj){
            if(toString.call(obj) == "[object Function]"){
                return true;
            }
        },
    });
    var Swerer = X.Swerer;
    Swerer = {};
    // Note:
    // When we are refering to Swerer in a Swerer function we can use the keyword 'this'
    /*

        Swerer.get("file.type", function(){
            func(arg);
        });

    */
    // Xhr (XML Http Request) is built into Swerer
    (XMLHttpRequest) ? Swerer.xhr = new XMLHttpRequest() : Swerer.xhr = new ActiveXObject("Microsoft.XMLHTTP");
    Swerer.getFile = function(file){
        var xhttp = this.xhr, content;
        if(this.readyState == 4 && this.status == 200){
            content = this.responseText;
        }
        xhttp.open("GET", file, true);
        xhttp.send();
        return content;
    };

如果您发现jsfiddle发布任何问题,我会尝试修复它。谢谢!

1 个答案:

答案 0 :(得分:0)

我必须承认我只专注于代码的XHR部分,但这应该是这样的:

&#13;
&#13;
// Xhr (XML Http Request) is built into Swerer
(XMLHttpRequest) ? Swerer.xhr = new XMLHttpRequest() : Swerer.xhr = new ActiveXObject("Microsoft.XMLHTTP");
Swerer.getFile = function(file){
    var xhttp = this.xhr;
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
           return xhttp.responseText;
        }
    };
    xhttp.open("GET", file, true);
    xhttp.send();
};
&#13;
&#13;
&#13;