jQuery.getScript()

jQuery.getScript( url, [ success(data, textStatus) ] ) 返回: XMLHttpRequest

描述: 通过 HTTP GET 请求从服务器载入并执行一个 JavaScript 文件

  • version added: 1.0jQuery.getScript( url, [ success(data, textStatus) ] )

    url一个包含发送请求的URL字符串。

    success(data, textStatus)当请求成功后执行的回调函数。

这是一个快速的AJax处理函数,相当于:

$.ajax({
  url: url,
  dataType: 'script',
  success: success
});

通过返回JavaScript的文件回调。通常不会有用作为该脚本已经执行到了这一点。

这个脚本在全局环境中已经执行,所以指向其他变量和使用jQuery函数。包含的脚本必须有一些效果在当前的页面上:

$('.result').html('<p>Lorem ipsum dolor sit amet.</p>');

通过引用这个文件名,脚本被包含进来并执行:

$.getScript('ajax/test.js', function() {
  alert('Load was performed.');
});

Examples:

Example: 我们动态加载新的官方jQuery 颜色动画插件,一旦该插件加载完成就会触发一些颜色动画。

<!DOCTYPE html>
<html>
<head>
  <style>.block { 
   background-color: blue; 
   width: 150px; 
   height: 70px;
   margin: 10px; 
}</style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>
  <button id="go">&raquo; Run</button>

<div class="block"></div>

<script>$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: 'pink' }, 1000)
      .animate( { backgroundColor: 'blue' }, 1000);
  });
});</script>

</body>
</html>

Demo:

Example: 加载并执行test.js文件。

$.getScript("test.js");

Example: 加载并执行test.js文件,当执行完成就显示一个警告。

$.getScript("test.js", function(){
   alert("Script loaded and executed.");
 });
jQuery 1.6 API 中文版Clove整理、修订