[BlogEntry] Returning and Executing JavaScript from a Rails URL


AuctionRelay.com has been running in Tomcat for a few years. A simple "include" script tag is all it takes to make AuctionRelay add HTML to the middle of an existing web page. The trick is in using the document.write command to make executable JavaScript write visible HTML at the location in the document where it executes.

I'm now in the process of rewriting AuctionRelay to run on Ruby on Rails (shouldn't that really be Rails on Ruby?). This morning, it was time to tackle the issue of setting the HTTP Content-Type header in the response, so that the browser would recognize that the response was executable JavaScript, and not displayable HTML. (Of course, the executable JavaScript is responsible for squirting in the displayable HTML, but that's the kind of convoluted world we've created for ourselves.)

I can browse to http://localhost:3000/js/test, which includes the line

<script src="http://localhost:3000/js/free?id=option_insight"/>

and see something like this:
in the midst of the original HTML page. (What you see here is still the output of the Java version.)


class JsController < ApplicationController

  def out
    @sellerId = @request.params['id'].to_s
    $mylog.debug("free request for " + @sellerId)
    if $freeSellers[@sellerId].nil?
      $mylog.debug("Not found - instantiating...")
      $freeSellers[@sellerId] = Ebay.new
      $mylog.debug("Already exists.")
    @headers["Content-Type"] = "text/javascript"

  def test


<script src="http://localhost:3000/js/out?id=option_insight"/>


document.write('<table border=1 align=center><caption><br/>My eBay feedback rating is\
<a href="http://feedback.ebay.com/ws/eBayISAPI.dll?ViewFeedback&userid=<%= @sellerId %>" target="_blank">\
<%= $freeSellers[@sellerId].feedback %>\
<td colspan=4 align=center>Display your live auctions on any web site for free at\
<a href="http://www.auctionrelay.com" target="_blank">AuctionRelay.com</a></table>');

One of the things I learned the hard way is that the string you pass to document.write must either be on a single line or use backslashes for continuations. (I was trying to make out.rhtml readable. Duh. Hindsight is 20/15 here.) Fortunately, the Firefox JavaScript Console gave me an error message that made me realize what was going on. Unfortunately, it took me 15 minutes of head-scratching to even think to look at it and recognize that the problem was with the actual JavaScript syntax and not something server-side.

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge