Section 6.9. Trying things out


6.9. Trying things out

Ready to take Boards 'R' Us for a little test drive? Make sure you've finished the exercise on the last two pages, and made those changes to your copy of boards.js. If you're not sure about your answers, you can compare them to ours in the back of this chapter, on page 366. Then save your changes, fire up your web browser, and load boards.html.

Here's how boards.html starts out. Click "Show Me the Money"...

...and you should get updated totals for all three products, without any nasty page reloads.

Looks like Katie is making sales in all three lines.

Wow! Time to raise your fees for working on the Boards report!

I'm telling you, Doc. I'm so much happier these days. I've finally found a way to say so much more... XML has really done the trick.

Dr. Zigmund: Ex-zellent. Zo you find that you are listened to now?

Server: Oh, yes. And I'll even admit... that guy with the tree farm has really helped out a lot.

Dr. Zigmund: Tell me more about zat...

Server: Well, at first, I was sending back XMLwhich was great, I'm telling you, nobody was asking me about comma-separated values or anything like that anymoreand browsers totally understood what I was saying. But it seemed that people were having trouble using what I was saying.

Dr. Zigmund: Oh, really? Why do you zink zat was?

Server: Well, it turns out they were using the plain text version of my XML response. So they were trying to break up the XML on their own. Sheesh, what a pain that must have been! And lots of people were screwing things up. Really bad.

Dr. Zigmund: And how did you handle zis new confusion?

You keep saying XML is better because it's not proprietary, and that it's a "standard." But that Boards 'R' Us XML uses elements like <boardsSold> and <bootsSold>. How is that standard? I mean, who else is gonna use those elements?

XML is a standard... ...but how you use it isn't.

XML is a specification that the World Wide Web Consortium (W3C) works and agrees on. That means that when you say XML, everyone knows what you mean. But XML is really a metalanguage: a language for defining other languages. So, in the Boards app, you used XML, but you defined your own elements that had names that worked well with the Boards 'R' Us app.

If you wanted to update Break Neck Pizza's server to return XML, you'd probably use different elements, perhaps with names like <deliveryTime> and <orderConfirmation>. The code on your server and the JavaScript code that you write must use the same element names, or nothing is going to work.

XML is a metalanguage: it defines other XML languages.

This is XML. It defines what an element is, what an attribute is, and how things like angle brackets, < and >, are supposed to be used. XML is a metalanguage.

<XML>

I still think XML is better than some weird made-up format. I mean, there will always be tools to work with XML, like the DOM, right?

Sometimes XML is great... ...and sometimes it's not.

XML is a popular data format, and you'll find tools like the DOM in every language. You don't have to worry about the order of elements in an XML document when you're using the DOM, and you don't need any special parsing code. So XML is a great idea for representing data.

But XML has its dark side, too: it takes a lot of text to say just a little in XML. All those angle brackets can really add up! And, as you'll see in the next chapter, there are plenty of other good options, like JSON.

Don't try to use XML for everything.

 This is an XML document. You have to use elements and attributes according to the XML standard, but you can define your own element and attribute names to create your own XML  language, just for your app. <?xml version="1.0" encoding="utf-8"?>     <totals>       <boards-sold>1710</boards-sold>       <boots-sold>315</boots-sold>       <bindings-sold>85</bindings-sold> </totals> 

Hey, I bet it's just as easy to send an XML request as it is to receive an XML response.

Well, there's a little more to it...

It turns out that you've got to do a good bit of work to send XML... in fact, quite a bit more work than it took to receive XML from the server. Most of the time, the effort you'll have to put into sending XML just isn't worth it. First, you'll need to send the XML in a POST request...

Sure, that makes sense. Because XML can get pretty long, and there's that maximum URL length on GET requests, right?

That's right.

Even the short XML response from the Boards server took up almost 200 characters!

It doesn't take a lot of data before an XML document gets pretty long. You'll definitely need to use a POST request. Additionally, you'll need to let the server know that you're sending it XML, not name/value pairs.

That's easy, too. I bet we can use a different Content-Type request header, right?

You can use the setRequestHeader()

method on your request object to tell the server that you're sending it XML, like this: You've really got this stuff down!

 request.setRequestHeader("Content-Type", "text/xml"); This tells the server that the content type of the incoming message is XML, in text format. 

And now I can just use the DOM to work with my XML, and send over the DOM tree.

And there's the problem!

Look at the "Content-Type" request header on the last page... it's "text/xml". That tells the server that it can expect XML, but in a text format. That's not the same as a DOM tree.

In fact, there's no easy way to send a DOM tree to a web server. You'd basically have to write code that parses the DOM tree in reverse; it would need to take each node in the DOM tree and write it out as text. That's called serialization, and it's not an easy task.

Hmm... that is starting to sound like a lot of work. But I guess I could just create XML as text, and send that, right?

Why would you do that?

After all the work you've done to learn how to use the DOM, it seems sort of silly to go back to text, doesn't it? In fact, it's pretty easy to make a mistake writing XML manually; that's part of why the DOM is so powerful. It helps keep you from making mistakes in your XML document's structure.

And besides, what exactly are you getting out of all the extra work involved in sending XML to a server instead of name/value pairs using plain old text?

You are back? I zought you were cured! What zeems to be the problem?

Server: I finally found a way to communicate... to be heard... to be understood...

Dr. Zigmund: Yes, yes, zee XML... is it not working anymore?

Server: No, it's great... I LOVE zee XML... I mean, "the" XML. But now everyone is trying to talk to me in XML.

Dr. Zigmund: And zere's a problem with zat?

Server: Well, yes! What was wrong with text? What happened to the days of simple name/value pairs? Now everyone is sending me these long XML documents, but they're saying the same things as when they were using simple name/value pairs.

Dr. Zigmund: And how does zat make you feel?

Server: Make me feel? It makes me feel bloated, and beaten down! Now I've got to parse the XML just to get the same values out of it that I could get instantly before.

And then I've got to make sure there aren't any errors. Just the tiniest little mistake in the XML, and everything blows up. Then the browser yells at me, and... oh, I just don't think I can take this!

Dr. Zigmund: Zo you want to abandon zee XML?

Server: No! No, I love being able to say so much when I respond to a request, and XML lets me do that. I just don't understand why everyone thinks that they have to speak XML to me. It just doesn't make sense...

Dr. Zigmund: It zeems to me that it's best to zend you zee plain text, and leave zee XML to you. Yes?

Server: Exactly! It's so simple... oh, I hate my life. Why, oh why?

My, my... zose are a lot of questions. I would zay, just remember my two golden rules: leave zee XML to zee server, and it's probably all your muh-zer's fault.

Apparently Dr. Zigmund is reading Head Rush Ajax, and perhaps a bit too much Freud...

Frequently asked questions?

Q:

If we want the server to return XML in its response, shouldn't we use XML to make our request, too?

A:

Not at all. The format you use for making your request has nothing to do with the format the server uses in its response. You could use plain text for the request and response, text for the request and XML for the response, XML for both the request and response, or even XML for the request and text for the response.

Q:

And if we're sending XML, we just need to set the request header, right?

A:

If you're making an XML request, you need to use a POST request, set the "Content-Type" of the request to "text/xml" using setRequestHeader(), and then send your XML in text form using the send() method of the request object.

Other than those few special steps, you'll send the request just like you would send a normal text request.

Q:

I still don't see why I can't just use the DOM and send my DOM tree to the server.

A:

You can use the DOM to build an XML request, but you can't just send your DOM document directly to the server. You'd have to get the text version of the DOM, and then send that instead of the actual DOM objects themselves.

Q:

Why? Wouldn't it be better to just send the DOM directly, if working with XML as text is so bad?

A:

Well, it does seem like sending the DOM directly would be simpler. But it's not easy to send objects across a network, especially using the Ajax request model.

Besides that, there really aren't any advantages to sending XML instead of just simple name/value pairs. So for the most part, XML would only complicate your requests, not make them simpler.

Q:

I read about this JavaScript toolkit that would convert my DOM tree to a text XML document. Can't I just use that toolkit, and then send the XML it creates on to the server?

A:

Sure, there's nothing wrong with that approach. But remember, you're really not gaining anything by using XML in your request. You already can send multiple values using name/value pairs, and that format is a standard that any server will recognize. So even if you could use XML, you probably don't want to.

Q:

So there's never a time when I should send a request in XML?

A:

Just about the only time it makes sense to send an XML request is if the server you're talking to only accepts XML. For instance, you might need to talk to a web server that only accepts SOAP requests, which is a particular XML format. Other than these special cases, though, name/value pairs are almost always the better choice for sending requests.


WHICH DATA FORMAT?

Welcome to this week's edition of "Which Data Format?" You've got to decide which data format is best for the 5 examples below. Be careful: some are requests, while others are responses. Good luck!

                             Text or XML      Top 10 iTunes                                      downloads of       2006 <?php require('lib.php');                                function go() { $myVar = ... return ... } Request today's house                                     blend Update journal with new                                          entry Number of hobbits that fit                                  in a Volkswagen <?php require('lib.php');                               function go() { $myVar = ... return ... } ?> Play "When It                                     Falls" next  


6.9.1. 60 Second Review

  • XML, the extensible markup language, lets you structure your data using elements and attributes.

  • Most server-side scripts and programs can create XML responses to send back to browser requests.

  • XML allows a server's response to include more than one piece of information, without requiring proprietary data formats or special formatting.

  • The responseText property of a request object returns the text version of any XML document returned by a server.

  • You can get the DOM representation of an XML document returned by a server-side component using the requestXML property of the request object.

  • If a server doesn't set the Content-Type response header to "text/xml", many browsers won't correctly set the responseXML property of the request object.

  • When the browser receives an XML response from a server, it creates a DOM tree representing the document.

  • You can send XML documents as well as receive them, although it takes a special toolkit or custom code to send a DOM representation of an XML document.

  • Creating XML manually, using plain text, is error-prone and usually requires a lot of effort.

  • For most requests, name/value pairs sent as plain text are the best solution, and require less processing by both your JavaScript and the web server to which you're sending the request.

Just Do It

It's time to put everything you've learned so far into action. Below is the updatePage() callback function for the Boards app. We've filled in all the blanks for you, so check your answers against ours, and make sure you feel like you understand all this code.

 function updatePage() {   if (request.readyState == 4) {     if (request.status == 200) {       // Get the updated totals from the XML response       var xmlDoc = request. responseXML ;       var xmlBoards =         xmlDoc. xmlDoc("boards-sold")[0];       var totalBoards = xmlBoards.firstChild.nodeValue;       var xmlBoots =         xmlDoc. getElementsByTagName("boots-sold")[0];       var totalBoots = xmlBoots.firstChild.nodeValue;       var xmlBindings =         xmldoc. getElementsByTagName ("binding-sold")[0];       var totalBindings = xmlBindings.firstChild.nodeValue;      // Update the page with new totals      var boardsSoldEl =        document. getElementById("boards-sold");      var bootsSoldEl =        document. getElementById("boots-sold");      var bindingsSoldEl =        document. getElementById("bindings-sold");      var cashEl = document. getElementById("cash");      replaceText(boardsSoldEl,totalBoards);      replaceText(bootsSoldEl, totalBoards);      replaceText(bindingsSoldEl, totalBindings); You could have these three lines of code in any order, as along as you keep the element and its value together.      // Figure out how much cash Katie has made on boards      var boardsPriceEl =        document.getElementById("boards-price");      var boardsPrice = getText(boardsPriceEl); 

     var boardsCostEl =       document.getElementById("boards-cost");     var boardsCost = getText(boardsCostEl);     var cashPerBoard = boardsPrice - boardsCost;     var cash = cashPerBoard * totalBoards;     // Figure out how much cash Katie has made on boots     var bootsPriceEl =       document.getElementById("boots-price");       var bootsPrice = getText(bootsPriceEl);       var bootsCostEl = document.getElementById("boots-cost");      var bootsCost = getText(bootsCostEl);      var cashPerBoot = bootsCost -bootsPrice ;      cash = cash + (cashPerBoot * totalBoots); This was a little bit tricky... you've got to keep a running total, so begin with the current value of cash, and then add to that.     // Figure out how much cash Katie has made on bindings     var bindingsPriceEl =       document.getElementById("bindings-price");     var bindingsPrice = getText(bindingsPriceEl);     var bindingsCostEl =       document.getElementById("bindings-cost");     var bindingsCost = getText(bindingsCostEl);     var cashPerBinding = bindingsPrice - bindingsCost;     cash = cash + (cashPerBinding * totalBindings);     // Update the cash for the slopes on the web form     cash = Math.round(cash * 100) / 100;     replaceText(cashEl, cash);     } else     alert("Error! Request status is " + request.status);   } } 


WHICH DATA FORMAT?

Welcome to this week's edition of "Which Data Format?" You've got to decide which data format is best for the 5 examples below. Good luck!

 Top 10 iTunes downloads of 2006 <?php require('lib.php');                                  function go() { $myVar = ... return ... } ?> Since the server has to send back more than one piece of information, XML works well here. Request today's house blend                                 There's almost never a need to send requests using XML. Update journal with new entry                                 Number of hobbits that fit in a Volkswagen <?php require('lib.php');                                 function go() { $myVar = ... return ... } ?> XML would work here, but since there's only a single piece of data, plain text is much easier. Play "When It Falls" next                                 





Head Rush Ajax
Head Rush Ajax (Head First)
ISBN: 0596102259
EAN: 2147483647
Year: 2004
Pages: 241

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net