如何缩小Ajax代码量?

我正在创建完全基于Ajax的网站,所以所有的操作都调用不同的JS函数,因此我在我的每个函数中都使用这个Ajax代码,这使我的函数成为一个大代码。

if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
        var getData=xmlhttp.responseText;
        if(getData=="something") {
            /* 
            code goes here
            */
        }
        else {
            /* 
            code goes here
            */
        }
    }
}
xmlhttp.open("GET","mypage.php",true);
xmlhttp.send();

因此,我想问一下,我是否应该使用只包含在Ajax代码上面的不同函数,并在全局上声明我的变量getData?每当我需要它时,我再调用它?

以下是我想用的方法:

var getData=""; /*declaring var Globally (I read it like this dont know right)*/

function oneAjax(checkPage) {
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            getData=xmlhttp.responseText;
            /*now check further in the function which called it*/
        }
    }
    xmlhttp.open("GET",checkPage+".php",true);
    xmlhttp.send();
}

它会与其他运行操作产生冲突吗?或者能为我的问题提供其他正确的解决方案吗?

If you're not going to use an off-the-shelf library, you should pass a "callback" to oneAjax:

function oneAjax(checkPage, done, fail) {

     ...

     xmlhttp.onreadystatechange = function() {
         if (xmlhttp.readyState == 4) {
             if (xmlhttp.status == 200) {
                 done(xmlhttp.responseText, xmlhttp.status);
             } else {
                 fail(xmlhttp.status);
             }
          }
     };

 }

Adjust the parameters passed to the callbacks to suit your requirements.

To use:

oneAjax('mypage', function(text, status) {
    // success
    console.log(status);
}, function(status) {
    // failure
    console.log(status);
});

why don't you use Jquery or something like this? Such library will much shorten your statements and this will be much easier to write.

But still if you want to do it by your own you should read about javascript promises. On msdn there is a nice tutorial how to solve your problem: Asynchronous Programming in JavaScript with “Promises”

I think using the jQuery library would be better and provide a better low level abstraction

<!-- add a protocol if on local ex: http: -->
<script src="//code.jquery.com/jquery-1.10.0.min.js"></script>
$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

It also offers features like JSONP to get around cross domain issues