返回值:jqXHRjQuery.getScript(url, [success(script, textStatus, jqXHR)])
通过 HTTP GET 方式从服务器请求一个 JavaScript 文件,并执行它。
-
1.0 新增jQuery.getScript(url, [success(script, textStatus, jqXHR)])
url (String) 将要被请求的 URL 字符串。success(script, textStatus, jqXHR) (Function) 可选参数,当请求成功后执行的回调函数。
这是一个 Ajax 函数的简写形式,它等价于:
$.ajax({
url: url,
dataType: "script",
success: success
});
载入的脚本会以全局的上下文来执行,所以它可以访问页面上其它的变量,或者运行 jQuery 函数。即,被加载的脚本同样作用于当前页面,例如:
Success 回调函数
这里的回调函数会传入返回的 JavaScript 文件。但这通常没什么用,因为此时脚本已经运行过了。
$(".result").html("<p>Lorem ipsum dolor sit amet.</p>");
通过文件名就可以动态载入并运行脚本了。例如:
$.getScript('ajax/test.js', function(data, textStatus, jqxhr){
console.log(data); //data returned
console.log(textStatus); //success
console.log(jqxhr.status); //200
console.log('Load was performed.');
});
错误处理
从 jQuery 1.5 开始,你可以使用 .fail() 来处理错误:
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log( textStatus );
})
.fail(function(jqxhr, settings, exception) {
$( "div.log" ).text( "Triggered ajaxError handler." );
});
在 jQuery 1.5 之前,需要使用全局的 ajaxError() 回调函数,来处理 $.getScript() 的错误。例如:
$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
if (settings.dataType=='script') {
$(this).text( "Triggered ajaxError handler." );
}
});
缓存响应
默认情况下,$.getScript() 将缓存设置成 false。这种情况下,会在请求的 URL 后添加一个时间戳的请求参数,保证每次请求时,浏览器每次都会重新下载脚本。你可以重写这个功能,通过设置 $.ajaxSetup() 的 cache 属性:
$.ajaxSetup({
cache: true
});
Alternatively, you could define a new method that uses the more flexible $.ajax() method.
示例:
定义一个 $.cachedScript() 方法,允许取得经过缓存的脚本:
jQuery 代码:
jQuery.cachedScript = function(url, options) {
// allow user to set any option except for dataType, cache, and url
options = $.extend(options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax(options);
};
// Usage
$.cachedScript("ajax/test.js").done(function(script, textStatus) {
console.log( textStatus );
});
示例:
动态载入 jQuery 官方颜色插件,并且在载入成功后绑定一些色彩动画。
<!DOCTYPE html>
<html>
<head>
<style>
.block {
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
}</style>
<script src="jquery.min.js"></script>
</head>
<body>
<button id="go">» Run</button>
<div class="block"></div>
<script>
$.getScript("jquery.color.js", function() {
$("#go").click(function(){
$(".block").animate( { backgroundColor: "pink" }, 1000)
.delay(500)
.animate( { backgroundColor: "blue" }, 1000);
});
});
</script>
</body>
</html>