2013-06-04 151 views
1

我正在創建完全基於Ajax的網站,所以所有操作都調用不同的JS函數,因此我在每個函數中都使用這個Ajax代碼,這使得我的函數成爲一個大代碼。縮短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(); 
} 

它會創建與其他正在運行的行爲有關的任何衝突? 或爲我的問題提供任何正確的解決方案。

回答

2

如果你不打算使用一種現成的,現成的庫中,你應該通過一個「回調」到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); 
      } 
      } 
    }; 

} 

調整傳遞到回調,以滿足您的要求的參數。

要使用:

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

也許提供一個應如何調用oneAjax的例子。我認爲回調可能會讓初學者感到困惑。教程中的 –

1

你爲什麼不使用jQuery或類似的東西呢?這樣的圖書館將大大縮短你的陳述,這將更容易編寫。

但如果你想自己做,你應該閱讀關於JavaScript的承諾。 MSDN上有一個很好的教程如何解決你的問題:Asynchronous Programming in JavaScript with 「Promises」

+1

+ 1,對通常的「你沒有jquery? –

+1

jQuery不是一顆銀色的子彈。 –

+1

@FelixKling它是在拍攝自己的腳很好,雖然;-) – Alnitak

0

我想使用jQuery庫會更好,並提供一個更好的低層次的抽象

<!-- 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); 
}); 

它還提供了像JSONP功能得到解決跨域問題

+0

雖然JSONP並沒有特定於jQuery,但JSONP無非是定義一個函數,創建一個'腳本'元素並附加到文檔中。 –

+0

是的,但它已經具備了此功能,您不必將其編碼。jQuery已經擁有大量的功能,並且具有跨瀏覽器兼容性。 –

+0

當然,但它聽起來像你可以做一些你不能沒有的jQuery。我完全同意它更容易。 –