Its much simpler than XML but sufficient for representing many apps data

Its much simpler than xml but sufficient for

This preview shows page 240 - 242 out of 517 pages.

It’s much simpler than XML but sufficient for representing many apps’ data structures, and has become so popular that many RESTful APIs can serve either JSON or XML: you specify which one you want either by calling a different endpoint (URL) for each format or by passing a parameter in the REST API call. Since the JSON format is a proper subset of JavaScript’s built-in object notation, we could in principle just write var e=eval(j) to deserialize a JSON-encoded string j into a “live” JavaScript object e . In practice, modern browsers’ JSAPIs include a function JSON.parse which is not only much faster than eval but also safer: whereas eval will evaluate arbitrary (untrusted and possibly evil) JavaScript code, JSON.parse will raise an error if asked to parse anything other than valid JSON data structures. (JSONLint, listed in Figure 6.4 , validates the syntax of JSON expressions.) To use JSON in our client-side code, we must address three questions: 1. How do we get the server app to generate JSON in response to AJAX requests, rather than rendering HTML view templates or partials? 2. How does the client specify that it expects a JSON response, and how does it use the JSON response data to modify the DOM? 3. When testing AJAX requests that expect JSON responses, how can we use fixtures to “stub out the server” and test these behaviors in isolation, as we did in Section 6.7 ? 1 Review.first.to_json 2 # => "{\"created_at\":\"2012-10-01T20:44:42Z\", \"id\":1, \"movie_id\":1, 3 \"moviegoer_id\":2,\"potatoes\":3,\"updated_at\":\"2013-07-28T18:01:35Z\"}" Figure 6.26: Rails’ built-in to_json can serialize simple ActiveRecord objects by calling itself recursively on each attribute of the model. As you can see, it doesn’t traverse associations—the review’s movie_id and moviegoer_id are serialized to integers, not to the Movie and Moviegoer objects to which the integer foreign keys refer. You can effect more sophisticated serialization by overriding to_json in your ActiveRecord models.
Image of page 240
The first question is easy. If you have control over the server code, your Rails controller actions can emit JSON rather than XML or a Haml template by using render :json=> object , which sends a JSON representation of an object back to the client as the single response from the controller action. Like rendering a template, you are only allowed a single call to render per action, so all the response data for a given controller action must be packed into a single JSON object. render :json works by calling to_json on object to create the string to send back to the client. The default implementation of to_json can serialize simple ActiveRecord objects, as Figure 6.26 shows. 1 var MoviePopupJson = { 2 // ’setup’ function omitted for brevity 3 getMovieInfo: function() { 4 $.ajax({type: ’GET’, 5 dataType: ’json’, 6 url: $(this).attr(’href’), 7 success: MoviePopupJson.showMovieInfo 8 // ’timeout’ and ’error’ functions omitted for brevity 9 }); 10 return(false); 11 } 12 ,showMovieInfo: function(jsonData, requestStatus, xhrObject) { 13 // center a floater 1/2 as wide and 1/4 as tall as screen 14 var oneFourth = Math.ceil($(window).width()
Image of page 241
Image of page 242

You've reached the end of your free preview.

Want to read all 517 pages?

  • Spring '19
  • Dr.Marcos

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern

Stuck? We have tutors online 24/7 who can help you get unstuck.
A+ icon
Ask Expert Tutors You can ask You can ask You can ask (will expire )
Answers in as fast as 15 minutes
A+ icon
Ask Expert Tutors