2

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 ?

4
  • Store it as JSON data and retrieve it.
    – Win
    Commented Jun 7, 2017 at 9:40
  • If you have access to server code, set Access-control-Allow-Origin header to your ip or to *.
    – Supradeep
    Commented Jun 7, 2017 at 9:42
  • 1
    Possible duplicate of How to make cross domain request
    – Ivar
    Commented Jun 7, 2017 at 9:44
  • @suzo That's useless since the remote file is JS, not JSON. It cannot be used as data.
    – hindmost
    Commented Jun 7, 2017 at 9:46

1 Answer 1

1

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
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.