1. Utility Functions



$() $F() $A() $H() $R() Try.these()



說明:



$() 等同於document.getElementById()



$F() 可以傳回任何 form內元素的value



$A() 用來轉換 DOM NodeLists(如options)為 arrays



$H() 將array物件轉換成 Hash List



$R() new ObjectRange(lowerBound, upperBound, excludeBounds) 的簡化寫法



Try.these() 以一連串的 functions為參數,依次呼叫直到某一個function正確傳回結果



使用:



javascript:



var d = $('myDiv1'); -> 取得一個元素



var divs = $('myDiv1','myDiv2');-> 取得元素陣列



alert( $F('userName') ); -> 取得 userName.value;



var someNodeList = $('lstEmployees').getElementsByTagName('option'); -> 取得options的 list



var nodes = $A(someNodeList); -> 將 list轉換成array



nodes.each(function(node){ -> traversal



alert(node.nodeName + ': ' + node.innerHTML);



});



var a = { -> 定義 array 物件



first: 10,



second: 20,



third: 30



};



var h = $H(a); -> 將 array 轉換成 Hash



alert( h.toQueryString() ); //displays: first=10&second=20&third=30



function demoDollar_R(){



var range = $R(10, 20, false); -> ObjectRange繼承Enumerable,可產生10到 20的list物件



range.each(function(value, index){ -> 以 each 方法 iterate 所有物件



alert("range["+index+"]="+value);



});



}



function getXmlNodeValue(xmlNode){



return Try.these(



function() {return xmlNode.text;}, ->xmlNode.text 在某些 browsers可以運作



function() {return xmlNode.textContent;}->xmlNode.textContent在其他browsers可以運作



);



}



HTML:



< div id="myDiv1">



This is a paragraph






 





< div id="myDiv2">



This is another paragraph






 





< input type="text" id="userName" value="Joe Doe">





< select id="lstEmployees" size="10" >



















2. AJAX 物件



2.1 Ajax.Request 類別



< script>



function searchSales() {



var empID = $F('lstEmployees');



var y = $F('lstYears');



var url = 'http://yoursever/app/get_sales';



var pars = 'empID=' + empID + '&year=' + y;



// 產生 XMLHttpRequest 物件,設定URL, GET Method,參數為pars,取得結果時呼叫 showResponse



var myAjax = new Ajax.Request(



url,



{method: 'get', parameters: pars, onComplete: showResponse}



);



}



function showResponse(originalRequest)



{



//put returned XML in the textarea



$('result').value = originalRequest.responseText;



}







< select id="lstEmployees" size="10" >



















< select id="lstYears" size="3" >



















< br>< textarea id=result cols=60 rows=10 >



上面的html透過 http://yourserver/app/get_sales?empID=1234&year=1998 向 web ap server取得XML Response如下







< ajax-response>



< response type="object" id="productDetails">



< monthly-sales>



< employee-sales>



1234



1998-01



$8,115.36







< employee-sales>



1234



1998-02



$11,147.51



















2.2 Ajax.Responders



可以針對特定 event註冊function,每次當event發生時就會被呼叫



< script>



var myGlobalHandlers = {



onCreate: function(){



Element.show('systemWorking');



},



onComplete: function() {



if(Ajax.activeRequestCount == 0){



Element.hide('systemWorking');



}



}



};



Ajax.Responders.register(myGlobalHandlers);







< div id='systemWorking'>Loading...
 





2.3 Ajax.Updater



若web ap server回傳html資料,則以Ajax.Updater簡化處理



< script>



function getHTML()



{



var url = 'http://yourserver/app/getSomeHTML';



var pars = 'someParameter=ABC';



var myAjax = new Ajax.Updater( 'placeholder', url, { method: 'get', parameters: pars });



}







< input type=button value=GetHtml >



< div id="placeholder">
 





------------------------------



另一種使用 Ajax.Updater的方法



< script>



function getHTML()



{



var url = 'http://yourserver/app/getSomeHTML';



var pars = 'someParameter=ABC';



var myAjax = new Ajax.Updater( {success: 'placeholder'}, url, { method: 'get', parameters: pars, onFailure: reportError });



}



function reportError(request)



{



alert('Sorry. There was an error.');



}







< input type=button value=GetHtml >



< div id="placeholder">
 





-------------



如果你的 web ap server是回傳 JavaScript 代碼而不是單純的 HTML 標記,Ajax.Updater可以執行那段 JavaScript代碼,你只需在最後的參數中加入evalScripts: true屬性。



Javascript Function要寫成



sayHi = function(){ alert('Hi'); };



不可以寫成



function sayHi(){



alert('Hi');



}



3. Enumerating



3.1 Ruby style 的 loop



function showList(){



var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Meg'];



for(i=0;i

}



可以改寫為



function showList(){



var simpsons = ['Homer', 'Marge', 'Lisa', 'Bart', 'Meg'];



simpsons.each( function(familyMember){ alert(familyMember); });



}



3.2 Array



find method



< script>



function findEmployeeById(emp_id){



var listBox = $('lstEmployees')



var options = listBox.getElementsByTagName('option');



options = $A(options);



// 找到特定 emp_id的employee



var opt = options.find( function(employee){



return (employee.value == emp_id);



});



alert(opt.innerHTML); //displays the employee name



}







< select id="lstEmployees" size="10" >



< option value="5">Buchanan, Steven



< option value="8">Callahan, Laura



< option value="1">Davolio, Nancy







< input type="button" value="Find Laura" >



----------------------



findAll method



< script>



function showLocalLinks(paragraph){



paragraph = $(paragraph);



var links = $A(paragraph.getElementsByTagName('a'));



//find links that do not start with 'http'



var localLinks = links.findAll( function(link){



var start = link.href.substring(0,4);



return start !='http';



});



//now the link texts



var texts = localLinks.pluck('innerHTML');



//get them in a single string



var result = texts.inspect();



alert(result);



}







< p id="someText">



This < a href="http://othersite.com/page.html">text has



a < a href="#localAnchor">lot of



< a href="#otherAnchor">links. Some are



< a href="http://wherever.com/page.html">external



and some are local



 






< input type=button value="Find Local Links" >



4. PeriodicalExecuter



定時執行某個 function



function periodicalUpdate() {



new PeriodicalExecuter(refreshNews, 10); -> 每 10secs執行一次refreshNews



}



function refreshNews() {



//Ajax code to grab news and update DOM



}



************XMLHttpRequest Object*************



http://www.w3schools.com/xml/xml_http.asp



The XMLHttpRequest object is not a W3C standard.



Methods



abort() 取消目前的 request



getAllResponseHeaders() 以字串回傳所有 http headers



getResponseHeader("headername") 回傳特定header的value



open("method","URL",async,"uname","pswd")



指定request的 method, URL, and other optional attributes of a request



Methods可以是"GET", "POST", or "PUT"



async參數指定 request要同步或非同步處理, true -> 非同步



send(content) 傳送request



setRequestHeader("label","value") 增加header欄位 名稱為 "label" 值為 "value"



Properties



onreadystatechange 每次state改變的時候,會呼叫這個 event hander



readyState 傳回物件的狀態



0 = uninitialized



1 = loading



2 = loaded



3 = interactive



4 = complete



responseText 以字串取得回傳結果



responseXML 以XML取得回傳結果



status 回傳HTTP command 結果的狀態(e.g. 404 for "Not Found" or 200 for "OK")



statusText 以字串回傳 HTTP command 結果的狀態(e.g. "Not Found" or "OK")



http://www.xulplanet.com/references/objref/XMLHttpRequest.html



提供其他IE不支援 的Properties與 Methods



例如onload onerror onprogress



引用自:http://home.pchome.com.tw/home/cctg_yaocl/prototype.js.note.htm

狼翔月影 發表在 痞客邦 PIXNET 留言(0) 人氣()