Tải bản đầy đủ (.pdf) (7 trang)

Hướng dẫn lập trình web bằng ASP.NET

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (231.86 KB, 7 trang )

<span class='text_page_counter'>(1)</span><div class='page_container' data-page=1>

<b>Project1: </b>

<b>ONLINE CLASS VIEWER</b>


<b>Tài li</b>

<b>ệu hướng dẫn </b>

<b>– K</b>

<b>ỹ</b>

<b> thu</b>

<b>ật AJAX</b>



1. Gi

ới thiệu



Bình thường, mỗi khi browser gởi 1 u cầu lên server thì nó phải reload lại trang web, tức là
yêu cầu server gửi lại toàn bộ trang web.


Kĩ thuật Ajax (Asynchronous Javascript And Xml) giúp cho browser có thể gửi yêu cầu đến


server và nhận response mà không cần reload lại trang web. Ngồi ra, request này có thể được


thực hiện 1 cách bất đồng bộ ( trong quá trình thực hiện request, người dùng vẫn có thể tương


tác với trang web)


Kĩ thuật này sử dụng đối tượng <b>XMLHttp</b> để thực hiện các truy vấn lên server.


2. S

ử dụng lớp XMLHttp



Ta sẽ sử dụng javascript để thao tác trên đối tượng XMLHttp.


<i><b>2.1. T</b><b>ạo đối tượng XMLHttp:</b></i>


Bước đầu tiên cần phải thực hiện trong việc sử dụng đối tượng XMLHttp là phải tạo nó.


Đối với các trình duyệt khác nhau thì việc tạo đối tượng này sẽ khác nhau.


Đối với Internet Explorer (IE), đối tượng này được cài đặt dưới dạng 1 <b>ActiveXObject</b>.


Do đó, để tạo được nó, cần phải thực hiện câu lệnh javascript sau:



var oXmlHttp = new ActiveXObject("Microsoft.XMLHttp");


Trong đó Microsoft.XMLHttp là loại đối tượng ActiveXObject cần tạo.


Tuy nhiên, có nhiều phiên bản IE khác nhau nên để đối tượng XMLHttp cũng có nhiều


phiên bản khác nhau.


Các phiên bản này là:


 Microsoft.XMLHttp


 MSXML2.XMLHttp


 MSXML2.XMLHttp.3.0


 MSXML2.XMLHttp.4.0


 MSXML2.XMLHttp.5.0


</div>
<span class='text_page_counter'>(2)</span><div class='page_container' data-page=2>

Đối với các trình duyệt : Mozilla Firefox, Safari, và Opera thì câu lệnh javascript để tạo
đối tượng XMLHttp giống nhau:


var oXmlHttp = new XMLHttpRequest();


Như vậy, để tạo được đối tượng XMLHttp cho mọi trình duyệt ta dùng đoạn javascript


</div>
<span class='text_page_counter'>(3)</span><div class='page_container' data-page=3>

<i><b>2.2. S</b><b>ử dụng đói tượng XMLHttp</b></i>



Sau khi đã tạo đối tượng XMLHttp, ta bắt đầu thực hiện việc tạo request đến server.
Bước đầu tiên là gọi phương thức open, dùng để khởi tạo đối tượng. Phương thức này
nhận vào 3 tham số:


 <b>Request Type</b>: là 1 chuỗi cho biết loại request cần thực hiện, có thể là GET hoặc


POST.


 <b>URL</b>: là chuỗi URL cho biết địa chỉ cần gởi request đến.


 <b>Async</b>: là 1 giá trị boolean, cho biết request có được thực hiện 1 cách bất đồng bộ


hay không.


Tham số này rất quan trọng, nó xác định cách thức mà javascript thực hiện request. Khi
được thiết lập là <b>true</b>, request sẽ được thực hiện 1 cách bất đồng bộ, và các đoạn lệnh


javascript vẫn tiếp tục được thực hiện mà khơng cần phải chờ response từ server. Vì vậy,


ta cần phải cài đặt 1 hàm xử lí sự kiện có nhiệm vụ chờ response từ server. Nếu async là
<b>false</b> thì các đoạn lệnh javascript kế tiếp sẽ không được thực hiện cho đến khi server gởi


xong dữ liệu về. Nếu như thời gian mà server trả response về là lâu thì sẽ gây bất tiện vì


người dùng không thể tương tác được với trang web trong khoảng thời gian đó. Vì vậy,


cách tốt nhất là gán cho async giá trị <b>True</b> khi gọi hàm <b>open</b>.


<b>Ví dụ</b>: Để thực hiện 1 request yêu cầu server trả về nội dung file info.txt nằm trên thư



mục chứa trang web trên server thì ta thực hiện như sau:


oXmlHttp.open("get", "info.txt", true);


Đối tượng XMLHttp có 1 thuộc tính là <b>readyState</b>, tham số này sẽ thay đổi khi mà


request được thực hiện và khi client nhận được response từ server. Thuộc tính này có 5
giá trị như sau:


 0 (Uninitialized): Đối tượng mới đựơc tạo nhưng hàm open chưa được gọi.
 1 (Loading): Hàm open mới được gọi nhưng request chưa được gởi


 2 (Loaded): Request vừa mới được gởi


 3 (Interactive): Client đã nhận được một phần response từ server


 4 (Complete): Tất cả dữ liệu đã được server gởi về client và kết nối đã đóng lại.


Mỗi lần thuộc tính readyState thay đổi giá trị thì sự kiện <b>readystatechange</b> được phát


</div>
<span class='text_page_counter'>(4)</span><div class='page_container' data-page=4>

Trong đoạn lệnh ở trên, ta định nghĩa 1 hàm <b>onreadystatechange</b> có chức năng hiển thị 1
dialog box để thông báo.


Bước cuối cùng là gọi hàm <b>send(), </b>hàm này sẽ thực sự gởi request lên server. Hàm này
có 1 tham số, đó là chuỗi chứa phần body của request. Đối với request loại GET thì
khơng cần phần body này, do đó, ta gọi hàm send với tham số là NULL. Đối với loại


request là POST thì tham số này khác null.
oXmlHttp.send(null);



Sau khi gọi hàm này thì request được gởi đi, khi tồn bộ dữ liệu được nhận về thì hàm
<b>onreadystatechange</b> sẽ được gọi và ở đây, ta sẽ thực hiện các xử lí tương ứng với dữ liệu


nhận được. Dữ liệu này được lấy thông qua 1 trong 2 thuộc tính <b>responseText</b> hoặc


<b>responseXML.</b>


Thuộc tính responseText chứa chuỗi response trong khi responseXML chứa 1 đối tượng


tài liệu XML. Thuộc tính responseXML chỉ được dùng khi loại dữ liệu trả về là text/xml.


Trong trường hợp yêu cầu nội dung file info.txt trong ví dụ trên thì ta chỉ cần dùng thuộc


tính responseText.


Nếu sử dụng thuộc tính responseXML thì cần tìm hiểu thêm về <b>DOMDocument </b>vì


responseXML chính là 1 đối tượng DOMDocument. Có thể tìm thơng tin về loại đối
tượng này trong MSDN 2003 với từ khóa “DOMDocument”.


Một đoạn code ví dụ sử dụng thuộc tính responseXML


var xmldoc = httpRequest.responseXML;


var root_node = xmldoc.getElementsByTagName(root).item(0);


alert(root_node.firstChild.data);


<b>Các vấn đề khác </b>



Một vấn đề nữa được đặt ra là, sau khi thực hiện, có thể request khơng thành công. Chẳng


hạn như, nếu ta yêu cầu server trả về nội dung file info.txt nhưng trên server không có


file này thì lỗi sẽ phát sinh.


Để giải quyết trường hợp bị lỗi, ta dùng 2 thuộc tính khác của lớp XMLHttp là <b>status</b> và
<b>statusText</b>. Nếu <b>status</b> có giá trị là 200 thì request thành cơng, ngược lại, request thất


bại, khi đó, thơng tin lỗi sẽ được chứa trong thuộc tính <b>statusText</b>.


</div>
<span class='text_page_counter'>(5)</span><div class='page_container' data-page=5>

hàm <b>getResponseHeader. </b>Phần thông tin quan trọng nhất trong response header là
<b>Content-Type</b>, phần này cho biết dữ liệu lấy về thuộc loại gì (text, html, image...)


Cũng có thể lấy tất cả các thông tin từ response header như sau:


Trong khi thực hiện request, ta cũng có thể thêm các thơng tin vào phần header của
request, đây có thể là các thơng tin bất kì.


</div>
<span class='text_page_counter'>(6)</span><div class='page_container' data-page=6>

Zip Code: <input type="text" name="txtZipCode" value="" /><br />
Phone: <input type="text" name="txtPhone" value="" /><br />
E-mail: <input type="text" name="txtEmail" value="" /></p>
<p><input type="submit" value="Save Customer Info" /></p>
</form>


<div id="divStatus"></div>


You'll note that the onsubmit event handler has now changed to call the function sendRequest()
(although the event handler still returns false to prevent actual form submission). This method first
assembles the data for the POST request and then creates the XMLHttp object to send it. The data must


be sent in the format as a query string:


name1=value1&name2=value2&name3=value3


Both the name and value of each parameter must be URL-encoded in order to avoid data loss during
transmission. JavaScript provides a built-in function called encodeURIComponent() that can be used
to perform this encoding. To create this string, you'll need to iterate over the form fields, extracting and
encoding the name and value. The getRequestBody() function handles this:


function getRequestBody(oForm) {
var aParams = new Array();


for (var i=0 ; i < oForm.elements.length; i++) {


var sParam = encodeURIComponent(oForm.elements[i].name);
sParam += "=";


sParam += encodeURIComponent(oForm.elements[i].value);
aParams.push(sParam);


}


return aParams.join("&");
}


This function assumes that you will supply a reference to the form as an argument. An array (aParams)
is created to store each individual name-value pair. Then, the elements of the form are iterated over,
building up a string and storing it in sParam, which is then added to the array. Doing this prevents


multiple string concatenation, which can lead to slower code execution in some browsers. The last step
is to call join() on the array, passing in the ampersand character. This effectively combines all the
name-value pairs with ampersands, creating a single string in the correct format.


String concatenation in most browsers is an expensive process because strings are immutable, meaning
that once created, they cannot have their values changed. Thus, concatenating two strings involves first
allocating a new string and then copying the contents of the two other strings into it. Repeating this
process over and over causes a severe slowdown. For this reason, it's always best to keep string


</div>
<span class='text_page_counter'>(7)</span><div class='page_container' data-page=7>

oXmlHttp.open("post", oForm.action, true);
oXmlHttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");


oXmlHttp.onreadystatechange = function () {
if (oXmlHttp.readyState == 4) {


if (oXmlHttp.status == 200) {


saveResult(oXmlHttp.responseText);
} else {


saveResult("An error occurred: " + oXmlHttp.statusText);
}


}
};


oXmlHttp.send(sBody);
}



As with previous examples, the first step in this function is to get a reference to the form and store it in
a variable (oForm). Then, the request body is generated and stored in sBody. Next comes the creation
and setup of the XMLHttp object. Note that the first argument of open() is now post instead of get,
and the second is set to oForm.action (once again, so this script can be used on multiple pages).
You'll also notice that a request header is being set. When a form is posted from the browser to a
server, it sets the content type of the request as application/x-www-form-urlencoded. Most
server-side languages look for this encoding in order to parse the incoming POST data properly, so it is very
important for it to be set.


The onreadystatechange event handler is very similar to that of the GET example; the only change is
the call to saveResult() instead of displayCustomerInfo(). The last line is very important, as the
sBody string is passed to send() so that it will become part of the request body. This effectively
mimics what the browser does, so all server-side logic should work as expected.


3. Advantages and Disadvantages of XMLHttp



Undoubtedly, you can see the advantage of using XMLHttp for client-server communication instead of
hidden frames. The code you write is much cleaner and the intent of the code is much more apparent
than using numerous callback functions with hidden frames. You have access to request and response
headers as well as HTTP status codes, enabling you to determine if your request was successful.
The downside is that, unlike hidden frames, there is no browser history record of the calls that were
made. The Back and Forward buttons do not tie in to XMLHttp requests, so you have effectively cut
off their use. It is for this reason that many Ajax applications use a mixture of XMLHttp and hidden
frames to make a truly usable interface.


</div>

<!--links-->

×