我正在寻找一种方法来包含外部 .js 文件并从该请求接收响应 header 。
<script src="external/file.js?onload=callback">
function callback(data) {
data.getAllResponseHeaders();
}
</script>
显然,这似乎行不通。
如何通过包含 javascript 获取响应 header ? 不能是第二次请求。
在您的回答中,请避免使用 jQuery。
感谢您的帮助。
工作示例 感谢 gaetanoM
oXmlHttp.withCredentials = true; is for CORS
oXmlHttp.responseType = 'text'; is for DOM input?
这是我现在使用的代码;
<script>
function loadScript(url) {
var oXmlHttp = new XMLHttpRequest();
oXmlHttp.withCredentials = true;
oXmlHttp.responseType = 'text';
oXmlHttp.open('GET', url, true);
oXmlHttp.onload = function () {
if( oXmlHttp.status >= 200 || oXmlHttp.status == XMLHttpRequest.DONE ) {
var x = oXmlHttp.getAllResponseHeaders();
console.log(x);
if(oXmlHttp.responseText !== null) {
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement("script");
oScript.language = "javascript";
oScript.type = "text/javascript";
oScript.defer = true;
oScript.text = oXmlHttp.responseText;
oHead.appendChild(oScript);
}
}
}
oXmlHttp.send();
}
loadScript("http://url/to/file.js");
</script>
最佳答案
getAllResponseHeaders(): The XMLHttpRequest.getAllResponseHeaders() method returns all the response headers, separated by CRLF, as a string, or null if no response has been received. If a network error happened, an empty string is returned.
这意味着您需要使用XMLHttpRequest 加载外部js:
此外,通过这种方式,您只需加载一次文件。
function loadScript(url) {
var oXmlHttp = new XMLHttpRequest();
oXmlHttp.onreadystatechange = function () {
if (oXmlHttp.readyState == XMLHttpRequest.DONE) {
if (oXmlHttp.status == 200) {
var x = oXmlHttp.getAllResponseHeaders();
console.log(x);
if (oXmlHttp.responseText != null) {
var oHead = document.getElementsByTagName('HEAD').item(0);
var oScript = document.createElement("script");
oScript.language = "javascript";
oScript.type = "text/javascript";
oScript.text = oXmlHttp.responseText;
oHead.appendChild(oScript);
}
} else {
console.log("Error", oXmlHttp.statusText)
}
}
}
oXmlHttp.open('get', url);
oXmlHttp.send();
}
loadScript("11.js?onload=callback");
关于javascript - 从包含外部 javascript 文件中检索响应 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46530285/