【发布时间】:2017-06-01 19:57:38
【问题描述】:
我解析一个网页,根据内容,我需要对我的本地主机进行 ajax 调用。 在本地主机上将是一个 PHP 脚本,它将通过 AJAX 交换数据,可能是 JSON 格式(我还不确定,仍在阅读和测试)。
这是一个插件,我尝试在 Google 页面上进行测试
我遵循这个简单的 ajax 示例:
https://www.w3schools.com/xml/ajax_xmlhttprequest_response.asp
我自己成功拨打了电话
//loadDoc("http://localhost/index.php", myCallback); <-- this NOT
//loadDoc("https://www.google.de", myCallback); <-- this WORKS
/*
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified (unknown)
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified (unknown)
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
*/
function loadDoc(url, cFunction) {
var xhttp;
xhttp=new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
cFunction(this);
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
function myCallback(xhttp) {
alert("I'm alive from my local server");
}
(大)问题是我发现“内容安全策略”不允许我调用其他域,即使我在自己的上下文中(我的浏览器,FF 53)。
现在看来,至少对于像我需要的 GET 请求,这可以通过在 DOM 中插入一个脚本来轻松欺骗,就像这样
尤其是 Rob W 的这篇很棒的帖子
Insert code into the page context using a content script
所以我尝试了这样,但仍然无法正常工作。
// var actualCode = ['/* Code here. Example: */' + 'alert(0);',
// '// Beware! This array have to be joined',
// '// using a newline. Otherwise, missing semicolons',
// '// or single-line comments (//) will mess up your',
// '// code ----->'].join('\n');
var script = document.createElement('script');
script.src = "http://localhost/index.php";
script.type = "text/javascript";
document.appendChild(script);
// script.textContent = actualCode;
// (document.head||document.documentElement).appendChild(script);
// script.remove();
安全不是问题,因为我只使用本地主机。 我在这里想念什么?
已编辑
这些是 Firefox 调试器显示的错误
Blocked loading mixed active content “http://localhost/index.php”[Learn More] axtest.js:16
Content Security Policy: Ignoring “'unsafe-inline'” within script-src: ‘strict-dynamic’ specified (unknown)
Content Security Policy: Ignoring “https:” within script-src: ‘strict-dynamic’ specified (unknown)
Content Security Policy: Ignoring “http:” within script-src: ‘strict-dynamic’ specified
【问题讨论】:
-
如果您的 CSP 不允许您访问远程脚本,但您想访问远程脚本……为什么不直接更改您的 CSP?
-
@Shilly — 这是 CSP 而不是 CORS。
-
感谢您的澄清,因此我补充说 PHP 知识是有限的。我对跨域 ajax 调用链接感到困惑。所以使用正确的 CSP 头而不是添加正确的 CORS 头。
-
@Quentin 我该怎么做?
标签: javascript ajax jsonp