Continued from Rails 3 Remote Links and Forms: A Definitive Guide.
Since writing the Rails 3 Remote Links & Forms Definitive Guide, one question keeps coming up:
How can we make our remote links and forms retrieve JS.ERB, instead of an HTML partial?
In the last article, we requested an HTML partial to be inserted into the page by our AJAX callbacks. But what if we want JavaScript to be executed? Or JSON or XML to be parsed? Or plain text to be displayed?
Spoiler Alert: this article concludes with a complete working example using js.erb.
First, we must understand the `:remote => true` process in Rails 3. It's equal parts Rails and jQuery magic. But don't worry, it's very little magic, bundled into a 4-step process:
In this article, we're exploring the different ways we can specify the format of the AJAX response and handle it accordingly, which actually spans all 4 steps above.
When the browser sends web requests back and forth between the browser and the server, part of the request/response header can specify the format of the content. When loading a page in the browser, the content type is typically inferred from the extension in the URL. jQuery, though, can directly set the data-type desired in the AJAX request header.
jQuery's `.ajax()` method provides an optional parameter called `dataType` to specify the desired data-type of the response. This allows jQuery to specify the format type in the request's HTTP Accept header, and then to encapsulate the response content in the appropriate data object for easier manipulation.
As of jQuery 1.4, if you do not specify the data-type of the response, jQuery will actually inspect the MIME type header of the response and make an "intelligent guess" as to the data-type, changing the data-type of the response object on-the-fly.
There's more information on the .ajax() documentation page, but the basic types are:
dataType | Behavior |
---|---|
"xml" | Returns an XML document that can be processed by jQuery. |
"html" | Returns HTML as plain text, but evaluates any ` |
Comments are loading...