jquery ajax script,jQuery.getScript()

This is a shorthand Ajax function, which is equivalent to:

1

2

3

4

5

$.ajax({

url: url,

dataType: "script",

success: success

});

The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page.

Success Callback

The callback is fired once the script has been loaded but not necessarily executed.

Scripts are included and run by referencing the file name:

1

2

3

4

5

6

$.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." );

});

Handling Errors

As of jQuery 1.5, you may use .fail() to account for errors:

1

2

3

4

5

6

7

$.getScript( "ajax/test.js" )

.done(function(script, textStatus){

console.log( textStatus );

})

.fail(function(jqxhr, settings, exception){

$( "div.log" ).text( "Triggered ajaxError handler." );

});

Prior to jQuery 1.5, the global .ajaxError() callback event had to be used in order to handle $.getScript() errors:

1

2

3

4

5

$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception){

if ( settings.dataType == "script" ) {

$( this ).text( "Triggered ajaxError handler." );

}

});

Prior to jQuery 3.5.0, unsuccessful HTTP responses with a script Content-Type were still executed.

Caching Responses

By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested. You can override this feature by setting the cache property globally using $.ajaxSetup():

1

2

3

$.ajaxSetup({

cache: true

});

Alternatively, you could define a new method that uses the more flexible $.ajax() method.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值