幾個月前因為專案需要,寫了三個 Ajax 相關的函式,整理出來與大家分享:
ajaxLoadPage——在不重新載入的前提下,載入一段 HTML 並放進指定容器。formToRequestString——把表單中的所有元素與值轉換成請求字串。ajaxFormSubmit——結合前兩者,完成無重新整理的表單提交。先說明一個限制:無重新整理的表單提交目前無法處理檔案上傳,這是瀏覽器安全設定使然。實務上要解決上傳問題,通常得改用 iframe 手法,相關做法搜尋一下就能找到不少。
網路上優秀的 Ajax 類別與函式庫已經很多,這幾個或許算不上什麼,但仍有參考的價值,於是就公開出來。
//@desc load a page(some html) via xmlhttp, and display on a container
//@param url the url of the page will load, such as "index.php"
//@param request request string to be sent, such as "action=1&name=surfchen"
//@param method POST or GET
//@param container the container object, the loaded page will display in container.innerHTML
//@usage
// ajaxLoadPage('index.php','action=1&name=surfchen','POST',document.getElementById('my_home'))
// suppose there is a html element of "my_home" id, such as "<span id='my_home'></span>"
//@author SurfChen <surfchen@gmail.com>
//@url https://www.surfchen.org/
//@license https://www.gnu.org/licenses/gpl.html GPL
function ajaxLoadPage(url, request, method, container)
{
method = method.toUpperCase();
var loading_msg = 'Loading...';// the text shows on the container on loading.
var loader = new XMLHttpRequest;// require Cross-Browser XMLHttpRequest
if (method == 'GET')
{
urls = url.split("?");
if (urls[1] == '' || typeof urls[1] == 'undefined')
{
url = urls[0] + "?" + request;
}
else
{
url = urls[0] + "?" + urls[1] + "&" + request;
}
request = null;// for GET method, loader should send NULL
}
loader.open(method, url, true);
if (method == "POST")
{
loader.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
loader.onreadystatechange = function(){
if (loader.readyState == 1)
{
container.innerHTML = loading_msg;
}
if (loader.readyState == 4)
{
container.innerHTML = loader.responseText;
}
}
loader.send(request);
}
GET 時會先判斷原網址是否已有查詢字串,再決定用 ? 還是 & 接上參數,避免拼出畸形網址。另外值得注意的是 readyState == 1 時就先塞入載入提示,讓等待期間有回饋。
//@desc transform the elements of a form object and their values into request string
//@param form_obj the form object
//@usage formToRequestString(document.form1)
//@notice this function can not be used to upload a file. if there is a file input element,
// the func will take it as a text input. because of the security, in most of the
// browsers, we can not upload a file via xmlhttp. a solution is iframe.
//@author SurfChen <surfchen@gmail.com>
//@license https://www.gnu.org/licenses/gpl.html GPL
function formToRequestString(form_obj)
{
var query_string = '';
var and = '';
for (i = 0; i < form_obj.length; i++ )
{
e = form_obj[i];
if (e.name != '')
{
if (e.type == 'select-one')
{
element_value = e.options[e.selectedIndex].value;
}
else if (e.type == 'checkbox' || e.type == 'radio')
{
if (e.checked == false)
{
break;
}
element_value = e.value;
}
else
{
element_value = e.value;
}
query_string += and + e.name + '=' + element_value.replace(/\&/g, "%26");
and = "&"
}
}
return query_string;
}
這個函式依元素型別分別處理:下拉選單取目前選取項,核取方塊與單選鈕只在被勾選時才納入,其餘直接取值。第一個參數用空字串起頭、之後才變成 & 的寫法,是為了讓串接出來的查詢字串開頭不會多出分隔符號。
要留意的是原版的兩個限制:勾選類元素在遇到未勾選時用了 break 而非 continue,會提早結束整個迴圈;而值只轉義了 &,中文與 =、+ 等字元仍有風險。實用時建議改用 encodeURIComponent() 逐一編碼,並把 break 改為 continue。
//@desc no refresh submit(ajax) by using ajaxLoadPage and formToRequestString
//@param form_obj the form object
//@param container the container object, the loaded page will display in container.innerHTML
//@usage ajaxFormSubmit(document.form1, document.getElementById('my_home'))
//@author SurfChen <surfchen@gmail.com>
//@license https://www.gnu.org/licenses/gpl.html GPL
function ajaxFormSubmit(form_obj, container)
{
ajaxLoadPage(form_obj.getAttributeNode("action").value,
formToRequestString(form_obj),
form_obj.method,
container)
}
這個函式本身幾乎沒有邏輯,只是把表單的 action、method 與序列化後的內容轉交給 ajaxLoadPage。這種「薄包裝」的設計讓三個函式各司其職、彼此不耦合,日後要換掉其中任一環節都不必改動其他部分。
這三個函式採用 GPL 授權釋出,用於專案前請先確認授權條款是否與你的專案相容。