tags:

views:

36

answers:

2

I want to load code and display it inside code tags (for syntax highlighting, etc.) like this:

<pre><code>alert("javascript loaded");</code></pre>

I am doing this in jQuery right now:

$.ajax({
  url: "/local/path.js",
  success: function(data) {
    alert("success");
    var code = $("<pre><code>" + data + "</code></pre>");
    $("body").append(code);
  }
})

...where "/local/path.js" is some code snippet we want to show as part of a blog post but don't want it to execute:

# /local/path.js (or /local/path.programming-language-ext)
alert("javascript loaded");

The problem is, before alert("success"); is even called, alert("javascript loaded"); is called. That shouldn't be executing, I want to load just a raw string. That is, I don't want jQuery to do any sort of processing on the response. How do I do that? This is all done without any server-side language.

A: 

Somehow, for some reason, jQuery is executing the response...

seems weird, have you tried just string in code variable?...

var code = "<pre><code>" + data + "</code></pre>";
$("body").append(code);

maybe try adding dataType

$.ajax({
  url: "/local/path.js",
  dataType: 'text',
  success: function(data) {
    alert("success");
    var code = $("<pre><code>" + data + "</code></pre>");
    $("body").append(code);
  }
})
Reigel
yeah, it happens before the success function is called, so this is too late. If I change the file extension name from `.js` to `.something-random`, it works fine. jQuery must be checking the file extension. how do i get around that??
viatropos
have you tried adding `dataType: 'text'` ? http://api.jquery.com/jquery.ajax/
Reigel
dataType vs. datatype...are you kidding me. thanks :)!
viatropos
+3  A: 

jQuery will

... intelligently try to get the results, based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

(From http://api.jquery.com/jQuery.ajax/, section dataType. Also, see "Data Types")

Therefore:

$.ajax({
  url: "/local/path.js",
  ...
  dataType: 'text'
});

Alternatively, you should be able to configure your server to send the files in /local/ as text/plain but that's probably not the way to go. At least, I prefer to be explicit in use, i.e., specify the type where I need it.

jensgram