jjclarkson
jjclarkson

Reputation: 5954

How do I prevent this javascript from being evaluated?

I am trying to build a web based code editor, and load javascript into a textarea value and I discovered quite by accident that the page is evaluating the code.

var url = 'local.js';
var timestamp = new Date().getUTCMilliseconds();
$.get(url, {r:timestamp}, function(data) {
    $("#scriptview").val(data);
    $("#editor").slideDown();
}); 

How do I prevent the GET request from evaluating the code? I am getting the source directly from a local file.

UPDATE: Changing the code to add the dataType fixed this problem. I couldn't get the $.get syntactic sugar just right so I'm using $.ajax

var url = 'local.js';
var timestamp = new Date().getUTCMilliseconds();
$.ajax({url:url, data: {r:timestamp}, success: function(data) {
       $("#scriptview").val(data);
       $("#editor").slideDown();
       return false;
}, dataType: "text"});

I still don't understand why the code inside the called file was being executed, I'm not appending to the body in a script tag or anything.

Upvotes: 0

Views: 195

Answers (1)

Quentin
Quentin

Reputation: 943571

jQuery.ajax accepts a dataType parameter. Setting it explicitly will:

  • Set the Accept header
  • Ignore the Content-Type of the response and parse the data as the format you say.

If you don't set it, then jQuery will infer the data type from the Content-Type of the response. This is usually a good thing!

In this case, you are requesting JavaScript (which will come with a Content-Type: text/javascript response header) but don't want it to be treated as JavaScript. jQuery does support "script" as a data type!

Set the dataType (to "text") to override the default handling.

(Credit to @freedomn-m for spotting the issue)

Upvotes: 2

Related Questions