[英]Retrieve response headers from including external javascript file
I am looking for a way to include an external .js file and receive the response headers from that request.我正在寻找一种包含外部 .js 文件并从该请求接收响应标头的方法。
<script src="external/file.js?onload=callback">
function callback(data) {
data.getAllResponseHeaders();
}
</script>
Obviously, this doesn't seem to work.显然,这似乎行不通。
How do I get the response header from including the javascript?如何从包含 javascript 中获取响应标头? It can not be a second request.
它不能是第二个请求。
In your answer, please avoid using jQuery.在您的回答中,请避免使用 jQuery。
Thanks for any help.谢谢你的帮助。
WORKING EXAMPLE Thanks to gaetanoM工作示例感谢 gaetanoM
oXmlHttp.withCredentials = true; is for CORS
oXmlHttp.responseType = 'text'; is for DOM input?
Here is the code I use now;这是我现在使用的代码;
<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.
getAllResponseHeaders() :XMLHttpRequest.getAllResponseHeaders() 方法以字符串形式返回所有响应标头,以 CRLF 分隔,如果未收到响应,则返回 null。 If a network error happened, an empty string is returned.
如果发生网络错误,则返回空字符串。
That means you need to load the external js with a XMLHttpRequest :这意味着您需要使用XMLHttpRequest加载外部 js:
Moreover, in this way you load only one time the file.而且,通过这种方式,您只加载一次文件。
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.