多次Eval或加载远程脚本 [英] Eval or load a remote script several times

查看:47
本文介绍了多次Eval或加载远程脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以加载远程脚本并对其进行评估?

Is it possible to load a remote script and have it eval'ed?

例如:

$(someelement).update("<script type='text/javascript' src='/otherscript.js'>");

并且在 otherscript.js 中:

alert('hi!');

这不起作用。我想在每次用户点击某些内容时加载该脚本。我想另一个选择是将该脚本的内容放在我的主脚本中(并根据需要进行评估),但这不是一个很好的方法。

That doesn't work. I want to load that script each time the user clicks something. I guess another option would be to put the contents of that script in my main script (and eval it as needed), but that's not a very good approach.

此外,如果这是可能的,是否可以从另一个域评估脚本?

Also, if this is possible, would it be possible to eval a script from another domain too?

推荐答案

不使用任何框架(谢谢到CodeJoust):

Without using any framework (with thanks to CodeJoust):

// a is the script to call
// b is the ID of the script tag (optional)

function scriptc(a,b){
  var __d=document;
  var __h = __d.getElementsByTagName("head")[0];
  var s = __d.createElement("script");
  s.setAttribute("src", a);
  s.id = b;
  __h.appendChild(s);
}

scriptc("http://example.com/someother.js");
// adds to DOM and it'll get loaded

但请注意因为脚本在其他域上可以访问您域中的敏感信息,例如PHP中的Cookie会话ID。

However take caution because the script on other domains can access sensitive information on your domain, such as the Session ID through cookies in PHP.

示例:

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>

<div id="cool">testing</div>

<script type="text/javascript">//<!--
function scriptc(a,b){
  var __d=document;
  var __h = __d.getElementsByTagName("head").item(0);
  var s = __d.createElement("script");
  s.setAttribute("src", a);
  s.id = b;
  __h.appendChild(s);
}

scriptc("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js");

// --></script>

</body>
</html>

加载之后,我使用Firebug来检查 $(#cool )。html()

After which is loaded, I use Firebug to examine $("#cool").html().

这篇关于多次Eval或加载远程脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆