use*_*235 6 javascript ajax google-chrome xmlhttprequest
我试图通过xhr获取http:// javascript文件,但我遇到了上面提到的错误.
这是我的代码:
function getXHR() {
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if (is_chrome) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var s = document.createElement('script');
s.textContent = xhr.responseText;
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
}
}
xhr.send();
}
}
Run Code Online (Sandbox Code Playgroud)
这仅适用于Chrome,因为我想在https://中使用该脚本,但Chrome会自动阻止http://中的任何内容.我从中获取脚本的服务器不运行https://我需要脚本/有多个脚本我宁愿不将所有脚本复制到数据文件中.
我遇到的错误:
XMLHttpRequest cannot load http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true. Origin https://mysite.com is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)
只需<script>直接插入标签而不是这个 XHR 包装器,然后将内容插入到标签中<script> 。
function getScript() {
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if (is_chrome) {
// generate script element and set its source
var s = document.createElement('script');
s.src = "http://api.widgets.org/widget/1.1.2/widget_api.js?autoCreate=false&log=true";
// remove the script element after loading
s.addEventListener( 'load', function(){ s.parentNode.removeChild(s); } );
(document.head||document.documentElement).appendChild(s);
}
}
Run Code Online (Sandbox Code Playgroud)
此外,我不知道为什么你尝试在加载后删除脚本元素。这不会影响该代码中创建的任何对象/方法/变量。
| 归档时间: |
|
| 查看次数: |
32317 次 |
| 最近记录: |