简体   繁体   中英

Javascript: How to read data from remote js file?

I have a javascript file from remote server and it contains a variable which has data which I want to access.

Js file:

http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs

Js file contain code like below

var MyItemData={"counts":{"q":1,"a":1,"r":2,"ar":4,"rr":0,"dq":1,"da":1,"c":0,"sdsd":0},"active":true};

I've used below code but it's giving error for cross-origin request block.

var target = 'http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs';
jQuery.get(target, function(data) {
                                        alert(data);
                                    });

Any other way to get the data ?

If the remote file is javascript and contains variable declaration as in your example, it will be available for other scripts on web page including your script. You only need to load this file as javascript and listen for its load event. When it fires you'll have access to that variable.

So the code might look like this:

var script = document.createElement('script');
script.src = target; 
script.addEventListener('load', function() {
    // at this moment MyItemData variable is accessible as MyItemData or window.MyItemData
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM