开发者

AJAX: advantages to using jQuery's .ajax() instead of XMLHttpRequest?

Is there any real advantage to using the jQuery AJAX function over the type of AJAX function shown below? Obviously, the syntax is a little cleaner / shorter - but is there any noticiable difference that would justify re-writing my existing ajax code?

var ajax = getXmlObject();
var url= '/addPartToCart.php?m=' + encodeURIComponent(m) + 
         '&q=' + qty + 
         '&refresh=' + randomString();

if (ajax.readyState == 4 || ajax.readyState == 0) {
    ajax.open("POST", url, true);
    ajax.onread开发者_Go百科ystatechange = function (){
        if (ajax.readyState == 4) {    

        }
    }; 
    ajax.send(null);
} 

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

UPDATE

I've reprogrammed all of my AJAX functions to use jQuery's .ajax(). I must say I've seen a notable improvement in speed and reliability.


You may want to give a look to jQuery's src/ajax.js source code. One reason it's 720 sloc, and not just 10 is mainly to:

  • Fix and wrap known inconsistencies between the different browsers. The comments will reveal many of these issues.

  • Provide extra features like handling JSONP through the same interface, event hooks, etc. And other syntactic sugar.


I'm not sure that it would be worth re-writing unless you are already using jQuery for other parts of your website. The primary advantage is that the code is a lot easier to read with jQuery, and it takes care of cross-browser compatibility issues for you.

Using jQuery solely for AJAX may not be the best idea though.


Being a newbie to JS and Jquery I can say that jQuery.Post(url); is a million times easier to read than above...:-)


It really depends on if you need the additional features that jquery ajax provides. I tend to send data as object literals instead of string concats. Also one feature I use very often is the ability to evaluate script tags within the response html. jQuery ajax handles these things very nicely.

If you are happy with the code the way it is then stick with it. I think you would find many places (besides ajax) to implement jQuery if you included it. :)


yes, and goto's w/ if statements can do everything a while loop, for loop, list comprehension, or an array map/filter/reduce can do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜