Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get <script> content as String

I tried using Javascript on demand to override cross domain problems.

So now I have something like that on my page:

<script id="scr1" src="{some other domain url}"></script>

The content of this script is a simply an array:

["hello", "world", "what", "where"]

I want to somehow get this content as string so I can eval it.
I wish I had some JS/JQuery method like

var v = eval($("#scr1").getContent());

Can you help me please?

Note: I can't use ajax as a solution.

like image 438
orshachar Avatar asked Dec 22 '22 16:12

orshachar


1 Answers

You should look up JSONP. What you want your script to return is the invocation of a callback with the data as the argument.

<script id="scr1" src="http://www.example.com/some/action?callback=cb" type="text/javascript></script>

The server side then, would produce the script contents:

cb( ["hello", "world", "what", "where"] );

Then on in your page, you'd need to have a function named cb that expects an array.

function cb(data) {
  // do something with the array
}

Of course, this expects the cooperation of the server to understand your callback parameter and respond appropriately. If you control the server, that's pretty easy to do. If not, then you'll need to use an API that is constructed to return JSONP. The callback parameter is a pretty standard name for such frameworks. If they don't have an API, then you need to proxy the request on your server, in which case you can use standard JSON.

FWIW, jQuery makes this pretty easy for APIs that expect to return JSONP.

$.getJSON( 'http://example.com/api/method?callback=?', data, function(result) {
     // do something with the json result
});

You can also use this with post/get/ajax methods as well, but getJSON is easier. Note that including the callback parameter automatically tells it to use a JSONP (script) request and automatically fills in the name of the callback it creates to wrap the (anonymous) callback function in the request.

like image 142
tvanfosson Avatar answered Dec 30 '22 08:12

tvanfosson