Tài liệu Developing facebookbapplications phần 9

  • Số trang: 19 |
  • Loại file: PDF |
  • Lượt xem: 60 |
  • Lượt tải: 0

Đã đăng 28936 tài liệu

Mô tả:

A JAX IN FBJS That code should look familiar to you. It’s the same code we would use for a normal Rails application. Facebooker takes care of hiding the Facebook-specific details from you. We’re now using real Ajax to do the same thing we did previously with Mock Ajax. Facebooker made the normal Rails helpers work for us, but only in a very simple case. To do much more using Ajax, we’re going to have to look at the guts of the Facebook Ajax library. Ajax Under the Covers Let’s take a look at how Ajax is implemented by Facebook. Facebook provides an Ajax5 object as an interface to the browser’s XmlHTTPRequest object. It provides a simple abstraction to your application, as you can see in the following code: var ajax=new Ajax(); ajax.responseType=Ajax.JSON; ajax.ondone = function(data) { // do something with the data } ajax.post('http://www.example.com/comments' , {"body" : "This is a comment" ,"receiver_id" : 4}); To make an Ajax request, we perform four steps: 1. Create an Ajax instance. 2. Choose a response type. 3. Provide a callback. 4. Call ajax.post. We can create a new Ajax object using var ajax=new Ajax();. Next, we decide what type of data we will request. We can choose to receive the response as FBML, JSON, or raw content. If we choose FBML, Facebook will process the data into a format that can be passed to setInnerFBML. If we choose raw content, we could receive either plain text or XHTML to pass to the setTextValue or setInnerXHTML methods, respectively. Once we’ve picked the type of data, we must give Facebook a method to call when the request is complete. We do this by setting the ajax.ondone method with a function reference. Usually, this method will do something with the data such as update the page. We can optionally provide a method to call when an error occurs by setting the ajax.onerror attribute. Finally, we call the ajax.post method to tell Facebook to start the request. There shouldn’t be many times when you need to revert to 5. The documentation is at http://wiki.developers.facebook.com/index.php/FBJS#Ajax. Report erratum Prepared exclusively for Alison Tyler this copy is (P1.0 printing, September 2008) 154 A JAX IN FBJS writing Ajax calls by hand, but understanding how they work can help you debug problems as they come up. Using JSON with Ajax So far, we’ve been limited to updating only one element at a time using Ajax. Let’s look at how we can use JSON to update both the list of comments and also a message element with a single request. We’ll start by changing our call to remote_form_for to make a request for JSON. To do this, we need to replace the update parameter with a success callback. Our success parameter is a JavaScript snippet that receives the JSON-formatted data in a variable named request:


- Xem thêm -