- jQuery.getScript()
- jQuery.getScript( url [, success ] ) Возвращает: jqXHR
- Добавлен в версии: 1.0 jQuery.getScript( url [, success ] )
- Успешная функция обратного вызова
- Обработка ошибок
- Кэширование ответа
- jQuery.getScript()
- jQuery.getScript( url [, success ] ) Returns: jqXHR
- version added: 1.0 jQuery.getScript( url [, success ] )
- Success Callback
- Handling Errors
- Caching Responses
- Examples:
- Demo:
- Books
- .load()
- .load( url [, data ] [, complete ] ) Returns: jQuery
- version added: 1.0 .load( url [, data ] [, complete ] )
- Callback Function
- Request Method
- Loading Page Fragments
- Script Execution
- Additional Notes:
- Examples:
jQuery.getScript()
jQuery.getScript( url [, success ] ) Возвращает: jqXHR
Описание: Загружает JavaScript файл с сервера при помощи GET HTTP запроса и затем исполняет его.
Добавлен в версии: 1.0 jQuery.getScript( url [, success ] )
Это сокращенная функция Ajax эквивалентна коду:
$.ajax(
url: url,
dataType: "script",
success: success
>);
Скрипт выполняется в глобальном контексте, поэтому он может ссылаться на другие переменные и использовать функции JQuery. Подключенный сценарий может иметь определенное влияние на текущую страницу.
Успешная функция обратного вызова
Функция обратного вызова исполняется после того как он будет загружен, но необязательно до выполнения.
Скрипты подключаются и выполняются по имени файла:
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr )
console.log( data ); // Данные с сервера
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Загрузка была выполнена." );
>);
Обработка ошибок
Начиная с 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, только глобальный обработчик ошибок Ajax запросов .ajaxError() можно использовать для обработки ошибок метода $.getScript() :
$( "div.log" ).ajaxError(function( e, jqxhr, settings, exception )
if ( settings.dataType == "script" )
$( this ).text( "Triggered ajaxError handler." );
>
>);
Кэширование ответа
По умолчанию, $.getScript() устанавливает настройку cache в значение false . Это добавит метку времени к строке запроса в URL адрес для гарантированного предотвращения кэширования браузером. Вы можете переопределить это поведение, при помощи глобального метода $.ajaxSetup() :
В качестве альтернативы, Вы можете определить новый более гибкий метод, при помощи $.ajax() .
- Ajax
- Глобальные Ajax события
- Вспомогательные методы
- Низкоуровневый интерфейс
- Сокращенные методы
- Базовые
- Пользовательские
- Затухание
- Скольжение
- События браузера
- Загрузка документа
- Прикрепление обработчиков
- Объект событие
- События формы
- События клавиатуры
- События мыши
- Class атрибут
- Копирование
- DOM Вставка вокруг
- DOM Вставка внутрь
- DOM Вставка вне
- DOM Удаление
- DOM Замена
- Общие аттрибуты
- Свойства стилей
- Манипуляция коллекциями
- Хранилище данных
- DOM методы элементов
- Методы установки
- Экземпляр объекта jQuery
- Глобальный объект jQuery
- Атрибут
- Базовые
- Базовые фильтры
- Фильтры потомков
- Фильтры содержимого
- Форма
- Иерархия
- jQuery расширение
- Фильтр видимости
- Фильтрация
- Обход
- Обход элементов
- Версия 1.3
- Версия 1.7
- Версия 1.8
- Версия 1.9
- Версия 1.10
- Версия 3.0
Русская документация по jQuery.
При использовании любых материалов с сайта ссылка на сайт обязательна.jQuery.getScript()
jQuery.getScript( url [, success ] ) Returns: jqXHR
Description: Load a JavaScript file from the server using a GET HTTP request, then execute it.
version added: 1.0 jQuery.getScript( url [, success ] )
This is a shorthand Ajax function, which is equivalent to:
$.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 and executed.
Scripts are included and run by referencing the file name:
$.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:
$.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:
$( "div.log" ).on( "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() :
Alternatively, you could define a new method that uses the more flexible $.ajax() method.
Examples:
Define a $.cachedScript() method that allows fetching a cached script:
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 );
>);
Load the official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded.
html>
html lang="en">
head>
meta charset="utf-8">
title>jQuery.getScript demo title>
style>
.block
background-color: blue;
width: 150px;
height: 70px;
margin: 10px;
>
style>
script src="https://code.jquery.com/jquery-3.7.0.js"> script>
head>
body>
button id="go">» Run button>
div class="block"> div>
script>
var url = "https://code.jquery.com/color/jquery.color-2.1.2.js";
$.getScript( url, function( )
$( "#go" ).on( "click", function( )
$( ".block" )
.animate(
backgroundColor: "rgb(255, 180, 180)"
>, 1000 )
.delay( 500 )
.animate(
backgroundColor: "olive"
>, 1000 )
.delay( 500 )
.animate(
backgroundColor: "#00f"
>, 1000 );
>);
>);
script>
body>
html>
Demo:
- Ajax
- Global Ajax Event Handlers
- Helper Functions
- Low-Level Interface
- Shorthand Methods
- Deprecated 1.3
- Deprecated 1.7
- Deprecated 1.8
- Deprecated 1.9
- Deprecated 1.10
- Deprecated 3.0
- Deprecated 3.2
- Deprecated 3.3
- Deprecated 3.4
- Deprecated 3.5
- Basics
- Custom
- Fading
- Sliding
- Browser Events
- Document Loading
- Event Handler Attachment
- Event Object
- Form Events
- Keyboard Events
- Mouse Events
- Class Attribute
- Copying
- DOM Insertion, Around
- DOM Insertion, Inside
- DOM Insertion, Outside
- DOM Removal
- DOM Replacement
- General Attributes
- Style Properties
- Collection Manipulation
- Data Storage
- DOM Element Methods
- Setup Methods
- Properties of jQuery Object Instances
- Properties of the Global jQuery Object
- Attribute
- Basic
- Basic Filter
- Child Filter
- Content Filter
- Form
- Hierarchy
- jQuery Extensions
- Visibility Filter
- Filtering
- Miscellaneous Traversing
- Tree Traversal
- Version 1.0
- Version 1.0.4
- Version 1.1
- Version 1.1.2
- Version 1.1.3
- Version 1.1.4
- Version 1.2
- Version 1.2.3
- Version 1.2.6
- Version 1.3
- Version 1.4
- Version 1.4.1
- Version 1.4.2
- Version 1.4.3
- Version 1.4.4
- Version 1.5
- Version 1.5.1
- Version 1.6
- Version 1.7
- Version 1.8
- Version 1.9
- Version 1.11 & 2.1
- Version 1.12 & 2.2
- Version 3.0
- Version 3.1
- Version 3.2
- Version 3.3
- Version 3.4
- Version 3.5
- Version 3.6
- Version 3.7
Books
Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath
.load()
.load( url [, data ] [, complete ] ) Returns: jQuery
Description: Load data from the server and place the returned HTML into the matched elements.
version added: 1.0 .load( url [, data ] [, complete ] )
Note: Prior to jQuery 3.0, the event handling suite also had a method named .load() . Older versions of jQuery determined which method to fire based on the set of arguments passed to it.
This method is the simplest way to fetch data from the server. It is roughly equivalent to $.get(url, data, success) except that it is a method rather than global function and it has an implicit callback function. When a successful response is detected (i.e. when textStatus is "success" or "notmodified"), .load() sets the HTML contents of the matched elements to the returned data. This means that most uses of the method can be quite simple:
If no element is matched by the selector — in this case, if the document does not contain an element with — the Ajax request will not be sent.
Callback Function
If a "complete" callback is provided, it is executed after post-processing and HTML insertion has been performed. The callback is fired once for each element in the jQuery collection, and this is set to each DOM element in turn.
$( "#result" ).load( "ajax/test.html", function( )
alert( "Load was performed." );
>);
In the two examples above, if the current document does not contain an element with an ID of "result," the .load() method is not executed.
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
Loading Page Fragments
The .load() method, unlike $.get() , allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
We could modify the example above to use only part of the document that is fetched:
$( "#result" ).load( "ajax/test.html #container" );
When this method executes, it retrieves the content of ajax/test.html , but then jQuery parses the returned document to find the element with an ID of container . This element, along with its contents, is inserted into the element with an ID of result , and the rest of the retrieved document is discarded.
jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as , , or elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.
Script Execution
When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed. An example of both cases can be seen below:
Here, any JavaScript loaded into #a as a part of the document will successfully execute.
However, in the following case, script blocks in the document being loaded into #b are stripped out and not executed:
$( "#b" ).load( "article.html #target" );
Additional Notes:
- Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
Examples:
Load another page's list items into an ordered list.