Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ajax In Action (2006).pdf
Скачиваний:
63
Добавлен:
17.08.2013
Размер:
8.36 Mб
Скачать

472CHAPTER 12

Live search using XSLT

12.1.4Sending the results back to the client

When the server returns the result of a live search, we can send the information back to the client in one of several ways. We can format the results as XML, plain text, or HTML tags. In previous examples, we created an XML document on the server. The JavaScript code on the client side then called XML DOM methods to build the results table on the client side by looping through the XML nodes. This process used two loops. The first loop was on the server when we built the XML document, and the second was the loop to build the HTML table on the client.

We can avoid the client-side XML DOM loop by building the HTML table on the server before we send it back, rather than building the XML file. With this technique, we concatenate HTML tags into a large string, similar to what we did to create the XML document. However, instead of building it with XML tags, we use table elements. The HTML string is returned to the client, and we can apply it directly to an element’s innerHTML property. In this case, we would use the XMLHttpRequest object’s responseText property since we would have no need to navigate through the nodes.

The problem with these techniques is that—whether it happens on the server or the client—there is a requirement to loop through the data and build the table dynamically. If we need to make changes to the table format in the future, it may be a tedious task, depending on the complexity of the table. Adding or subtracting a column may cause a problem, since we must alter the code inside the loop. We also need to take into account the extra quotes that are contained inside our string; we must make sure that we are escaping the quotes when building the string. Also, if we embed JavaScript into this HTML tag, it adds even more quotes and apostrophes to worry about—we have to verify that all of the tags are closed and that they are properly formatted. The only way we can do that effectively is by examining the text after we build the string.

One option that lets us avoid these problems is to use XSLT. With Ajax, it is possible to combine an XSLT file with an XML document and display the results, thus avoiding DOM methods. If a developer knows XSLT and is not great at coding JavaScript, this may be an excellent solution.

One thing to note about an Ajax search is that it does not require a postback to the server, and consequently the URL of the page does not change to match the search results. Therefore bookmarking the URL will not give us the results we want. In a classic search, such as Google, we can easily copy a URL from a page found by the search and paste it into an e-mail; when the recipient clicks the link,