服务器托管插件上的跨域 ajax,无需 jquery 或任何帮助程序库
我制作了一个小的 JavaScript 插件,可以在我的网页中使用它,可通过 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
进行 ajax 调用 < code>http://my_server/query?foo=bar 并向上面的页面添加更多元素,效果就像一个魅力。
现在,我想让这个插件可供其他人使用。想象一下,用户想要在 http://her_server/index.html
的网页上实现它,但现在她收到一个错误,
XMLHttpRequest cannot load http://my_server/query?foo=bar.
Origin http://her_server/index.html is not allowed by
Access-Control-Allow-Origin.
这是一个额外的问题。现在,我将插件托管在 http://my_server/myPlugin.js
上(是的,我希望这是一个服务器端插件),并且查询服务器是相同的 http:// /my_server/query?foo=bar
。然而,在未来,它们可能是不同的服务器。例如,位于 http://my_plugin_server/myPlugin.js
的插件和位于 http://my_query_server/query?foo=bar
的查询服务器。
最后,所有这一切都是在没有 jQuery 或任何其他库的帮助下完成的。我的ajax代码是
"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 ..
}
}
}
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 ..
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论