【问题标题】:Running JavaScript downloaded with XMLHttpRequest recursively递归运行使用 XMLHttpRequest 下载的 JavaScript
【发布时间】:2012-08-29 09:43:28
【问题描述】:

是否可以更改此代码,因此如果 http://www.myurl.com 重定向到应该运行的 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");

【问题讨论】:

标签: javascript ajax scripting download


【解决方案1】:

为什么不直接做:

$("head").append("<script src='http://myurl.com' type='text/javascript'></script>"); 

当然你可以不用 jquery 来做,但这就是它的要点。如果您只是从只需要 GET 参数(如果有的话)的 URL 中提取,那么添加一个包含它的新脚本元素会更容易(也更安全)。

这也将解决您的重定向问题,因为浏览器将遵循重定向。

【讨论】:

  • XHR 也将遵循重定向,但确实,脚本插入比 OP 尝试的更好
  • 如果你要使用 jQuery,你可以考虑使用jQuery.getScript()
  • 为什么?有没有你没有告诉我们的要求?
  • 它不仅用于 js 拉数据。请阅读下面我对 Jasper de Vries 的评论
  • 你仍然可以使用 jQuery。只是eval datajQuery.get() 返回。
【解决方案2】:

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

if ((xmlhttp.status == 200 || xmlhttp.status == 301) && xmlhttp.readyState == 4)

或者您可以选择允许除错误状态之外的所有状态:

if (xmlhttp.status < 400 && xmlhttp.readyState == 4)

【讨论】:

  • 添加此状态时不会评估 js。我尝试为状态 301 添加“else if”,然后使用新的 url 调用 include,但在脚本 eval 之后(假设脚本是:alert("hello");)它继续使用“www. example.com/alert("你好);出于某种原因..有什么建议吗?
  • 你能做一个console.logxmlhttp 吗?状态是否符合预期?你有responseText吗?
  • 好吧,我不知道为什么,但是在包含这个“else if”并编写它之后:((xmlhttp.status == 301) && (xmlhttp.readyState == 4)) - 检查状态是 4 它的工作!以前没用,但谁记得我之前写的:)
猜你喜欢
  • 2011-04-13
  • 2011-10-02
  • 2011-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
相关资源
最近更新 更多