Cross-domain JSON request?

后端 未结 2 1362
臣服心动
臣服心动 2020-12-09 18:26

Question:

I\'m trying to use JSON accross domains, but all i find is JSON parsers, which I don\'t need...
I\'ve read that it\'s possible to do cross-domain requ

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 19:01

    What you can do cross-domain is inject a script include:

    var s = document.createElement('script');
    s.src = 'http://someotherdomain/getMeMyJs.aspx?parameter=value';
    s.onload = someOptionalCallback;
    s.type = 'text/javascript';
    
    if(document.getElementsByTagName('head').length > 0)
        document.getElementsByTagName('head')[0].appendChild(s);
    

    Now, the code returned by that request will be executed immediately. If you want for that to interact with your code, you can make sure that it's being returned with all data wrapped in a function call:

    jsonCallback({ object: json, whatever: value });
    

    You can use that to build APIs, where you pass the name of a callback function as a request querystring parameter. Here's an example of such an API

提交回复
热议问题