Skip to content

Instantly share code, notes, and snippets.

@caryfitzhugh
Created January 11, 2012 16:58
Show Gist options
  • Save caryfitzhugh/1595616 to your computer and use it in GitHub Desktop.
Save caryfitzhugh/1595616 to your computer and use it in GitHub Desktop.
How to *really* do what I wanted in jquery
// I'm a dork of sorts, and like to make my xhr requests mime type .js in rails.
// It makes action files really easy to separate (.js files are for xhr, .html files are for html)
//
// I guess it could cause issues - maybe we should be creating an XHR/html mime type
// Regardless, it's what we do at my company... I guess b/c I wrote it.
//
// So that .js view file should return HTML. You can always execute the html if you need:
// <script> alert('this xhr response has JS!'); </script>
//
// Whereas you can't really do HTML inside JS very well.
//
// What I wanted to do was request it as JS, and then treat it like HTML.
//
// I read the ajax docs and thought this was the ticket:
{ /...
dataType: 'script html'
}
// That worked ok - since we never cared about success/error callbacks, just complete.
// We could always get the responseText, and I didn't think much about it. We saw some errors
// at times, but with everything going on 'it just worked' so...
// Now I do care, and realize, after debugging with inspector, that jquery makes the request
// and then pretends it is 'text'. It wants to convert from 'text' => the first field in dataType.
// Which is a *bad* conversion. I thought it started with the response being script and
// converted that into html. It is trying to convert your response => script => html.
//
// I contend that is Crazy.
//
// However, the solution is clear! Just say you want script, and then provide a custom
// converter to take text => script.
//
// In our case the "text script" converter does nada.
$.ajax({
url: $this.attr('href'),
// Request as script - then when converting it in to jquery, just
// pass it through.
converters: {
"text script": function(data) { return data; }
},
dataType: 'script',
success: function(data, textStatus, jqXHR) {
var $data = $(data);
$placeholder.ziplist_update($data);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment