问题描述:

I have made a little JavaScript plugin that I can use like so in my web page reachable at http://my_server/index.html

<div id="foo"></div>

<script type="text/javascript" src="http://my_server/myPlugin.js"></script>

<script type="text/javascript">

myPlugin.init();

</script>

myPlugin.js makes ajax calls to http://my_server/query?foo=bar and adds more elements to the above page and works like a charm.

Now, I want to make this plugin usable by others. Imagine a user wants to implement it on a web page at http://her_server/index.html Except, now she gets an error

XMLHttpRequest cannot load http://my_server/query?foo=bar.

Origin http://her_server/index.html is not allowed by

Access-Control-Allow-Origin.

An additional wrinkle. For now I have the plugin hosted on http://my_server/myPlugin.js (yes, I want this to be a server side plugin) and the query server is the same http://my_server/query?foo=bar. However, in the future, they may be different servers. For example, the plugin at http://my_plugin_server/myPlugin.js and the query server at http://my_query_server/query?foo=bar.

Finally, all this is to be done without the help of jQuery or any other library. My ajax code is

"getData": function (q) {

var uri = "http://my_server/query?foo=" + q;

var req = new XMLHttpRequest();

req.onreadystatechange = handler;

req.open("GET", uri, true);

req.send();

function handler(evt) {

if (req.readyState == 4 && req.status == 200) {

var json = eval('('+ req.responseText +')');

.. do something with json ..

}

}

}

相关阅读:
Top