Get the contents of <script> as a string

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

So now I have something like this on my page:

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

The contents of this script is just an array:

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

I want to somehow get this content as a string so that I can evaluate it.
I wish I had some kind of JS / JQuery method like

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

Can you help me?

Note. I can not use ajax as a solution.

+3
source share
3 answers

You should look for JSONP. What you want the script to return is a callback with data as an argument.

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

Then the server side will create the contents of the script:

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

cb, .

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

, , . , . , API, JSONP. callback . API, , JSON.

FWIW, jQuery API, JSONP.

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

post/get/ajax, getJSON . , JSONP (script) , , () .

+9

jquery.getScript

$.getScript('urlOfRemoveScript',function(script){
    var v = eval(script);
});

, 100% .

+2

So here is my contribution if someone really needs to find a way to read each script content.


  jQuery("script").each(function(){
    var scriptContent = this.innerText
    // do something with scriptContent
  })
+1
source

All Articles