2
\$\begingroup\$

I know there is a lot of libraries with this built in $.get() etc... but as for writing this in pure JavaScript how does this look?

var get_request;

ajaxRequest(function() {
    var activexmodes, i, _i, _len, _ref, _results;
    activexmodes = ['Msxm12.XMLHTTP', 'Microsoft.XMLHTTP'];
    if (window.ActiveXObject) {

        _ref = activexmodes.length;
        _results = [];

        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            i = _ref[_i];
            try {
                _results.push(new ActiveXObject(activexmodes[i]));
            } catch (_error) {}
        }
        return _results;
    } else if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else {
        return false;
    }
});

get_request = new ajaxRequest();
\$\endgroup\$
3
\$\begingroup\$

There are a couple issues with this code:

  1. You don't define a function in Javascript with ajaxRequest(function() { ... }); What you're doing there is calling function ajaxRequest and passing an anonymous function into it as the only parameter. It will throw a JS error as it is now, because ajaxRequest isn't defined.

    To define an ajaxRequest function, you would do either function ajaxRequest() { ... } or var ajaxRequest = function() { ... };.

  2. This code snippet:

    activexmodes = ['Msxm12.XMLHTTP', 'Microsoft.XMLHTTP'];
    _ref = activexmodes.length;
    
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        i = _ref[_i];
    

    will also throw a JS error because you're treating _ref like an Array when it's actually a Number. I'm guessing you meant to use activexmodes instead. _ref is completely unnecessary.

  3. Why do you declare all your variables at the very top of the function? It's bad practice because declaring your variables when you first need them tells anyone who reads your code that "this is the first time I'm using this variable." If you declare them all at the top, anyone else who reads it has to search through to make sure it's not used or modified anywhere else. (In this case it's harmless, but in larger functions it can become and issue.)

  4. To use the function, you should call it directly instead of using new:

    var get_request = ajaxRequest();   // probably should be named getX(),
                                       // like getAJAXRequest()
    
  5. I would be careful about returning false from the function. If that's a known return value and you're going to check for it everywhere you use it, then that's okay. But if you forget to support that rare case, the user will get some cryptic JS error somewhere down the line when you try to call get_request.open() or some other function.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.