AJAX - The Complete Reference

(avery) #1

Chapter 4: Data Formats 137


PART I


The two structures can, of course, be combined to create a more complex data structure:

[
{ Name: Moe, Hair : Straight, Stooge Number : 1} ,
{ Name: Larry, Hair : Curly, Stooge Number : 2} ,
{ Name: Curly, Hair : None, Stooge Number : 3}
]

The previous example looks surprisingly like JSON, but looking more deeply at YAML,
there are all sorts of other things to discover. For example, you can add comments using the
hash mark (#) character and even delimit documents using three dashes (---).

---
# Main Stooges
[
{ Name: Moe, Hair : Straight, Stooge Number : 1} ,
{ Name: Larry, Hair : Curly, Stooge Number : 2} ,
{ Name: Curly, Hair : None, Stooge Number : 3}
]
----
# Alternate Stooges
[
{ Name: Shemp, Hair : Wavey} ,
{ Name: Curly Joe, Hair : None }
]

There are many more structures in YAML but, for the purposes of the example, this is
good enough to give the flavor of the format.
Now, similar to JSON, the data will need to be encoded on the client side. In this case,
we resorted to a near-500 line library to do the job. There are many of these on the Web with
no clear winner so we won’t recommend any particular one. Interestingly in this example,
in order to encode the data into YAML, it is first put into a JSON format and then passed to
the appropriate encoding function.

var payloadYaml = new YAML();
payload = payloadYaml.dump([{"rating": ratingVal, "comment": comment }]);

When sending the encoded content, the Content-Type header, in this case, should be set to
text/x-yaml.

xhr.setRequestHeader("Content-Type", "text/x-yaml");
Free download pdf