最近在工作的時候總結了一套ajax的簡易使用方法,通用性極好,給我的工作帶來了不少效率上的提高,先貼出來給大家參考:
一,先建一個ajax.js的文件,文件的內容如下:
var http_request = false;
var callback_func;
function sendRequest(url, argstr, func, method) {
? http_request = false;
? callback_func = func;
? if (window.XMLHttpRequest) { // Mozilla, Safari,...
??? http_request = new XMLHttpRequest();
??? if (http_request.overrideMimeType) {
????? http_request.overrideMimeType('text/xml');
??? }
? } else if (window.ActiveXObject) { // IE
??? try {
????? http_request = new ActiveXObject("Msxml2.XMLHTTP");
??? } catch (e) {
????? try {
??????? http_request = new ActiveXObject("Microsoft.XMLHTTP");
????? } catch (e) {}
??? }
? }
? if (!http_request) {
??? alert('Giving up :( Cannot create an XMLHTTP instance');
??? return false;
? }
? http_request.onreadystatechange = alertContents;
?
? if (method == 'GET') {
??? http_request.open('GET', url + '?' + argstr, true);
??? http_request.send(null);
? } else {
??? http_request.open('POST', url, true);
??? http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=GBK");
??? http_request.send(argstr);
? }
}
function alertContents() {
? if (http_request.readyState == 4) {
??? if (http_request.status == 200) {
????? callback_func(http_request.responseText);
??? } else {
????? alert('There was a problem with the request.');
??? }
? }
}
二,在頁面使用如下代碼將js文件包含進來:
<script language=javascript src="ajax.js"></script>
三,在頁面調用sendRequest(...)方法:
如:<a href="javascript:sendRequest('hello.jsp',param,function,'GET')" >調用AJAX</a>
或:<input type="button" value="提交" onclick="sendRequest('getInfo.do',param,function,'POST')" />
注釋(以第一個為例):
hello.jsp:? 這個例子采用ajax通過一個鏈接請求hello.jsp頁面,
param:?? 為參數,可以為空,也可以不為空,比如name=value&password=123456,也可以通過把一個表單(form)的字段組合起來作為一個字符串傳遞
過去,???
?function: 是你自己寫的一個函數,用于處理返回的內容,一般的處理是
將返回的內容顯示在頁面,一個典型的例子:
???function search(str){
?????????alert(str); //用于調試.
????????myId.innerHTML = str;
?? }
GET: 是請求的方法,簡單的說,get代表請求一個資源,post代表提交參數并請求資源.
任何疑問,可以聯系本人:diego.liu@163.com