简体   繁体   中英

Queries on Javascript Libraries

I have been trying to look at how javascript libraries work to have a better idea in general, but I don't really understand them. I have a little programming knowledge in java and javascript, but the code below still seems a little complicated for me. I have extracted this codes from a example on david-tang.net website. Although there are explanation in it, but after reading it, I am still a little confused. It there anyone out there who can help me with this? Thanks in advance.

/*
 * ajax static method
 * example:
 * dQuery.ajax({
        url: 'ajaxResponse.php',
        data: 'fname=David&age=25',
        success: function (response) {}
    });
 */

dQuery.ajax = (function () {
    var xhr;
if (typeof XMLHttpRequest !== 'undefined') {
    xhr = new XMLHttpRequest();
}
else {
    var IEversions = ["Microsoft.XmlHttp",
                    "MSXML2.XmlHttp",
                    "MSXML2.XmlHttp.3.0",
                    "MSXML2.XmlHttp.4.0",
                    "MSXML2.XmlHttp.5.0"];

    for(var i=0, len = IEversions.length; i<len; i++) {
        try {
            xhr = new ActiveXObject(IEversions[i]);
            break;
        }
        catch(e) {
        }
    }      
}

return function (param) {
    var url = param.url+'?'+param.data;    
    function checkReadiness () {
        if (xhr.readyState < 4) {
            return;
        }
        else if (xhr.readyState === 4 && xhr.status === 200) {
            param.success(xhr.responseText);
        }
        else if (xhr.status !== 200) {
            alert('Ajax request failed');
        }
    }

    xhr.onreadystatechange = checkReadiness;
    xhr.open('get', url, true);
    xhr.send('');
}
})();

Source: [http://david-tang.net/]


dQuery.ajax({
        url: 'ajaxResponse.php',
        data: 'fname=David&age=25',
        success: function (response) {}
    });



return function (param) {
    var url = param.url+'?'+param.data;    
    function checkReadiness () {
        if (xhr.readyState < 4) {
            return;
        }
        <b> 
            else if (xhr.readyState === 4 && xhr.status === 200) {
            param.success(xhr.responseText); 
        </b>
        }
        else if (xhr.status !== 200) {
            alert('Ajax request failed');
        }
    }

    xhr.onreadystatechange = checkReadiness;
    xhr.open('get', url, true);
    xhr.send('');
}

does this means that the success function is mapped to the param.success when the readyState is 4 and xhr.status is 200? but where is the line which returns param to the function? such that whenever in javascript success:function(response) {} is called, the response is the param?


in the testQuery.js

(function (window, undefined) {

var testQuery = function(obj) {
    if (!(this instanceof testQuery)) {
        return new testQuery(obj);
}


testQuery.alertMessage = (function () {
    alert("alert");
})();

}) (window);

in the testQuery.html

<html>
<head>

<script src="testQuery.js"></script>
<script>

function click() {

testQuery.alertMessage({});

}

<body>

<input type="button" value="click" onclick="click()">

</body>
</html>

First of all, they create a closure . This is a function that can contain basically everything to execute and returns something in the end. What is returned is set to dQuery.ajax :

dQuery.ajax = (function() {
    // ...
})();

Inside the closure they first create an engine to use when making AJAX requests. In all sane browsers, the engine is XMLHttpRequest . In Internet Explorer you need to try out a lot of other ways, including ActiveX Objects, which is what they do next (iterating through all ActiveX Objects that can be used for AJAX and see whether it is available).

Then, they return a function, which is going to be stored in dQuery.ajax (because it is the thing returned by the closure). This function first concatenates the URL and query string, so that test.php and foo=bar becomes the valid URL test.php?foo=bar .

After that they create a function (inside the return function - that's possible), which is fired everytime the AJAX engine state changes. The point is that it fires this event more often than you'd like to. You basically only want to do something in case the response is received and everything is correct. So they break off the function in case readyState < 4 . When the state is 4 and the HTTP response code is 200 (which is OK - so successful), they call the function passed through the param parameter, in its turn passing the response text to that function.

Outside that function they just fire off the request.

So, if you call like:

dQuery.ajax({
             type:"POST",
             url: "ajax.php",
             data:"id="+id ,
             success: function(data){
                 //response is in the data
            });

then the URL has become ajax.php?id=123 (depending on the value of id ), the request is fired off (with GET as param.type is nowhere used - are you missing something perhaps?), and when it's complete, the success function is called where data is the response text.

Edit: In a function, you can call an argument if it is a function:

function foo(func) {
    func(12); // Call the function and pass 12 as its first argument
}

function addone(x) {
    alert(x + 1); // When arrived here, x === 12
}

foo(addone); // This will eventually alert 13

Edit2: In response to what you posted:

(function (window, undefined) { // Start the closure, good

var testQuery = function(obj) { // Create a testQuery object, fine
    if (!(this instanceof testQuery)) {
        return new testQuery(obj);
}


testQuery.alertMessage = (function () { // Add a function, OK
    alert("alert");
})();

}) (window); // Oops - end of closure already.
             // Things have been defined but not exposed.
             // Just do window.testQuery = testQuery before the end of the closure,
             // so that you can actually use testQuery outside the closure.
             // Currently, testQuery is only accessible inside the closure, but
             // obviously you'd like to use it anywhere.

Edit3 : You are defining a function by calling it. That is not really necessary. Just do (like you define testQuery ):

testQuery.alertMessage = function () {
    alert("alert");
};

Secondly, you have no closing } of the if clause:

if (!(this instanceof testQuery)) {
    return new testQuery(obj);
} // <-- important!

It then works as expected: http://jsfiddle.net/UFfSf/ .

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