Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/416.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
递归运行使用XMLHttpRequest下载的JavaScript_Javascript_Ajax_Scripting_Download - Fatal编程技术网

递归运行使用XMLHttpRequest下载的JavaScript

递归运行使用XMLHttpRequest下载的JavaScript,javascript,ajax,scripting,download,Javascript,Ajax,Scripting,Download,如果重定向到应该运行的js文件,是否可以更改此代码,使其递归工作 function include(scriptUrl) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", scriptUrl); xmlhttp.onreadystatechange = function() { if ((xmlhttp.status == 200) &

如果重定向到应该运行的js文件,是否可以更改此代码,使其递归工作

function include(scriptUrl)
{
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", scriptUrl);
        xmlhttp.onreadystatechange = function()
        {
            if ((xmlhttp.status == 200) && (xmlhttp.readyState == 4))
            {
                eval(xmlhttp.responseText);
            }
        };
        xmlhttp.send();
}
include("http://www.myurl.com");

当URL将您重定向到另一个位置时,它可能会给您一个301而不是200状态。在这种情况下,您的支票应为:

if ((xmlhttp.status == 200 || xmlhttp.status == 301) && xmlhttp.readyState == 4)
或者,您可以选择允许除错误状态以外的所有状态:

if (xmlhttp.status < 400 && xmlhttp.readyState == 4)
if(xmlhttp.status<400&&xmlhttp.readyState==4)
为什么不做:

$("head").append("<script src='http://myurl.com' type='text/javascript'></script>"); 
$(“head”)。追加(“”);
当然,您可以不使用jquery来完成它,但这就是它的jist。如果您只是从一个只需要GET参数(如果有的话)的URL中提取,那么添加一个包含它的新脚本元素就更容易(也更安全)


这也将照顾你的重定向问题,因为浏览器将遵循重定向。

不,这是自动完成的,看到重定向也会跟随XHR,但是,如果你想使用jQuery,脚本插入比OP Tres更好。为什么?你有什么要求没告诉我们吗?它不仅仅是用来拉数据的。请阅读下面我对Jasper de Vries的评论,您仍然可以使用jQuery。只需
eval
返回的
数据
。添加此状态时不会评估js。我试图为状态301添加'else if',然后用新的url调用include,但是在它评估脚本之后(假设脚本是:alert(“hello”);),它继续用“www.example.com/alert(“hello”)再次调用它;由于某种原因。。有什么建议吗?你能做一个
xmlhttp
console.log
?状态是否如预期的那样?你得到了一个
响应文本吗?
?我不知道为什么,但是在包含了这个“else if”并编写它之后:((xmlhttp.status==301)和&(xmlhttp.readyState==4))-检查状态是否为4它正在工作!它以前不起作用,但谁还记得我以前写过什么:)