jQuery에서 로딩 스피너를 표시하는 방법은 무엇입니까?
에서 프로토 타입 이 코드와 함께 "로드 ..."이미지를 표시 할 수 있습니다 :
var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars,
onLoading: showLoad, onComplete: showResponse} );
function showLoad () {
...
}
jQuery 에서는 다음 과 같이 서버 페이지를 요소에로드 할 수 있습니다.
$('#message').load('index.php?pg=ajaxFlashcard');
그러나 프로토 타입에서와 같이 로딩 스피너를이 명령에 어떻게 첨부합니까?
몇 가지 방법이 있습니다. 내가 선호하는 방법은 요소 자체의 ajaxStart / Stop 이벤트에 함수를 첨부하는 것입니다.
$('#loadingDiv')
.hide() // Hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
Ajax 시작 / 중지 기능은 Ajax 호출을 할 때마다 실행됩니다.
업데이트 : jQuery 1.8부터 문서에는 .ajaxStart/Stop
첨부해야한다고 명시 되어 document
있습니다. 위의 스 니펫은
var $loading = $('#loadingDiv').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
jQuery의 경우 사용합니다
jQuery.ajaxSetup({
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
},
success: function() {}
});
jQuery의 .ajax
함수를 사용하고 해당 옵션을 사용하고 beforeSend
로더 div와 같은 것을 보여줄 수있는 함수를 정의하고 성공 옵션에서는 해당 로더 div를 숨길 수 있습니다.
jQuery.ajax({
type: "POST",
url: 'YOU_URL_TO_WHICH_DATA_SEND',
data:'YOUR_DATA_TO_SEND',
beforeSend: function() {
$("#loaderDiv").show();
},
success: function(data) {
$("#loaderDiv").hide();
}
});
Spinning Gif 이미지를 가질 수 있습니다. 다음은 귀하의 색 구성표에 따라 훌륭한 AJAX 로더 생성기 인 웹 사이트입니다 : http://ajaxload.info/
AJAX 호출 직전에 애니메이션 이미지를 DOM에 삽입하고 인라인 함수를 사용하여 제거 할 수 있습니다.
$("#myDiv").html('<img src="images/spinner.gif" alt="Wait" />');
$('#message').load('index.php?pg=ajaxFlashcard', null, function() {
$("#myDiv").html('');
});
그러면 후속 요청에서 애니메이션이 동일한 프레임에서 시작됩니다 (필요한 경우). 이전 버전의 IE 는 애니메이션에 어려움이 있을 수 있습니다.
행운을 빕니다!
$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);
showLoad();
function showResponse() {
hideLoad();
...
}
http://docs.jquery.com/Ajax/load#urldatacallback
사용하는 경우 다음 $.ajax()
과 같은 것을 사용할 수 있습니다.
$.ajax({
url: "destination url",
success: sdialog,
error: edialog,
// shows the loader element before sending.
beforeSend: function () { $("#imgSpinner1").show(); },
// hides the loader after completion of request, whether successfull or failor.
complete: function () { $("#imgSpinner1").hide(); },
type: 'POST', dataType: 'json'
});
로딩 플러그인을 사용하십시오 : http://plugins.jquery.com/project/loading
$.loading.onAjax({img:'loading.gif'});
변형 : 기본 페이지 왼쪽 상단에 id = "logo"아이콘이 있습니다. 그런 다음 Ajax가 작동 할 때 스피너 gif가 투명하게 겹쳐집니다.
jQuery.ajaxSetup({
beforeSend: function() {
$('#logo').css('background', 'url(images/ajax-loader.gif) no-repeat')
},
complete: function(){
$('#logo').css('background', 'none')
},
success: function() {}
});
나는 원래 회신에 두 가지 변경으로 끝났다 .
- jQuery 1.8부터 ajaxStart 및 ajaxStop은에만 첨부해야
document
합니다. 이로 인해 일부 아약스 요청 만 필터링하기가 더 어려워집니다. 수 ... - ajaxSend 및 ajaxComplete로 전환 하면 스피너를 표시하기 전에 현재 ajax 요청을 조사 할 수 있습니다.
다음은 이러한 변경 후의 코드입니다.
$(document)
.hide() // hide it initially
.ajaxSend(function(event, jqxhr, settings) {
if (settings.url !== "ajax/request.php") return;
$(".spinner").show();
})
.ajaxComplete(function(event, jqxhr, settings) {
if (settings.url !== "ajax/request.php") return;
$(".spinner").hide();
})
또한이 답변에 기여하고 싶습니다. jQuery에서 비슷한 것을 찾고 있었으며 결국에는 결국 사용했습니다.
http://ajaxload.info/ 에서 로딩 스피너를 얻었습니다 . 내 솔루션은 http://christierney.com/2011/03/23/global-ajax-loading-spinners/의 간단한 답변을 기반으로합니다 .
기본적으로 HTML 마크 업과 CSS는 다음과 같습니다.
<style>
#ajaxSpinnerImage {
display: none;
}
</style>
<div id="ajaxSpinnerContainer">
<img src="~/Content/ajax-loader.gif" id="ajaxSpinnerImage" title="working..." />
</div>
그런 다음 jQuery 코드는 다음과 같습니다.
<script>
$(document).ready(function () {
$(document)
.ajaxStart(function () {
$("#ajaxSpinnerImage").show();
})
.ajaxStop(function () {
$("#ajaxSpinnerImage").hide();
});
var owmAPI = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=YourAppID";
$.getJSON(owmAPI)
.done(function (data) {
alert(data.coord.lon);
})
.fail(function () {
alert('error');
});
});
</script>
그것은 간단합니다 :)
로더 이미지를 나중에 Ajax 호출을 사용하여 컨텐츠를로드 할 동일한 태그에 지정하면됩니다.
$("#message").html('<span>Loading...</span>');
$('#message').load('index.php?pg=ajaxFlashcard');
스팬 태그를 이미지 태그로 교체 할 수도 있습니다.
아약스 이벤트에 대한 전역 기본값을 설정하는 것 외에도 특정 요소에 대한 동작을 설정할 수 있습니다. 아마도 수업을 바꾸는 것만으로 충분할까요?
$('#myForm').ajaxSend( function() {
$(this).addClass('loading');
});
$('#myForm').ajaxComplete( function(){
$(this).removeClass('loading');
});
스피너로 #myForm을 숨기는 CSS 예제 :
.loading {
display: block;
background: url(spinner.gif) no-repeat center middle;
width: 124px;
height: 124px;
margin: 0 auto;
}
/* Hide all the children of the 'loading' element */
.loading * {
display: none;
}
스피너가 작동하려면 비동기 호출을 사용해야합니다 (적어도 그것은 아약스 호출이 끝날 때까지 표시되지 않았으며 호출이 완료되고 스피너가 제거됨에 따라 신속하게 사라졌습니다).
$.ajax({
url: requestUrl,
data: data,
dataType: 'JSON',
processData: false,
type: requestMethod,
async: true, <<<<<<------ set async to true
accepts: 'application/json',
contentType: 'application/json',
success: function (restResponse) {
// something here
},
error: function (restResponse) {
// something here
}
});
$('#loading-image').html('<img src="/images/ajax-loader.gif"> Sending...');
$.ajax({
url: uri,
cache: false,
success: function(){
$('#loading-image').html('');
},
error: function(jqXHR, textStatus, errorThrown) {
var text = "Error has occured when submitting the job: "+jqXHR.status+ " Contact IT dept";
$('#loading-image').html('<span style="color:red">'+text +' </span>');
}
});
jQuery UI Dialog와 함께 다음을 사용했습니다. (아마 다른 아약스 콜백과 작동합니까?)
$('<div><img src="/i/loading.gif" id="loading" /></div>').load('/ajax.html').dialog({
height: 300,
width: 600,
title: 'Wait for it...'
});
는 ajax 호출이 완료 될 때 내용이 교체 될 때까지 애니메이션 로딩 gif를 포함합니다.
이것은 나에게 가장 좋은 방법입니다.
jQuery :
$(document).ajaxStart(function() {
$(".loading").show();
});
$(document).ajaxStop(function() {
$(".loading").hide();
});
커피 :
$(document).ajaxStart ->
$(".loading").show()
$(document).ajaxStop ->
$(".loading").hide()
자바 스크립트
$.listen('click', '#captcha', function() {
$('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />');
$.get("/captcha/new", null, function(data) {
$('#captcha-block').html(data);
});
return false;
});
CSS
#loading { background: url(/image/loading.gif) no-repeat center; }
이것은 특정 목적을위한 매우 간단하고 똑똑한 플러그인입니다 : https://github.com/hekigan/is-loading
나는 이것을한다:
var preloaderdiv = '<div class="thumbs_preloader">Loading...</div>';
$('#detail_thumbnails').html(preloaderdiv);
$.ajax({
async:true,
url:'./Ajaxification/getRandomUser?top='+ $(sender).css('top') +'&lef='+ $(sender).css('left'),
success:function(data){
$('#detail_thumbnails').html(data);
}
});
그 쪽이 맞는 거 같아요. 이 방법은 너무 전역 적입니다 ...
그러나 AJAX 호출이 페이지 자체에 영향을 미치지 않는 경우에 좋은 기본값입니다. (예를 들어 배경 저장). ( "global": false를 전달하여 특정 ajax 호출에 대해 항상 끌 수 있습니다.- jquery의 설명서를 참조하십시오.
AJAX 호출이 페이지의 일부를 새로 고치려는 경우 "로드 중"이미지가 새로 고친 섹션에만 적용되는 것을 좋아합니다. 어느 부분이 새로 고쳐 졌는지보고 싶습니다.
단순히 다음과 같이 쓸 수 있다면 얼마나 멋진 지 상상해보십시오.
$("#component_to_refresh").ajax( { ... } );
그리고이 섹션에 "로드 중"이 표시됩니다. 아래는 필자가 작성한 "로드"디스플레이를 처리하는 함수이지만 아약스에서 새로 고치는 영역에 따라 다릅니다.
먼저 사용법을 보여 드리겠습니다
<!-- assume you have this HTML and you would like to refresh
it / load the content with ajax -->
<span id="email" name="name" class="ajax-loading">
</span>
<!-- then you have the following javascript -->
$(document).ready(function(){
$("#email").ajax({'url':"/my/url", load:true, global:false});
})
그리고 이것은 기능입니다. 원하는대로 향상시킬 수있는 기본 시작입니다. 매우 유연합니다.
jQuery.fn.ajax = function(options)
{
var $this = $(this);
debugger;
function invokeFunc(func, arguments)
{
if ( typeof(func) == "function")
{
func( arguments ) ;
}
}
function _think( obj, think )
{
if ( think )
{
obj.html('<div class="loading" style="background: url(/public/images/loading_1.gif) no-repeat; display:inline-block; width:70px; height:30px; padding-left:25px;"> Loading ... </div>');
}
else
{
obj.find(".loading").hide();
}
}
function makeMeThink( think )
{
if ( $this.is(".ajax-loading") )
{
_think($this,think);
}
else
{
_think($this, think);
}
}
options = $.extend({}, options); // make options not null - ridiculous, but still.
// read more about ajax events
var newoptions = $.extend({
beforeSend: function()
{
invokeFunc(options.beforeSend, null);
makeMeThink(true);
},
complete: function()
{
invokeFunc(options.complete);
makeMeThink(false);
},
success:function(result)
{
invokeFunc(options.success);
if ( options.load )
{
$this.html(result);
}
}
}, options);
$.ajax(newoptions);
};
자신의 코드를 작성하지 않으려는 경우 다음과 같은 플러그인이 많이 있습니다.
서버 요청을 할 때마다 로더를 사용하려는 경우 다음 패턴을 사용할 수 있습니다.
jTarget.ajaxloader(); // (re)start the loader
$.post('/libs/jajaxloader/demo/service/service.php', function (content) {
jTarget.append(content); // or do something with the content
})
.always(function () {
jTarget.ajaxloader("stop");
});
이 코드는 특히 jajaxloader 플러그인 (방금 만든)을 사용합니다.
https://github.com/lingtalfi/JAjaxLoader/
내 아약스 코드는 다음과 같습니다. 실제로 비동기 : 주석 라인을 주석 처리했으며 스피너가 나타납니다.
$.ajax({
url: "@Url.Action("MyJsonAction", "Home")",
type: "POST",
dataType: "json",
data: {parameter:variable},
//async: false,
error: function () {
},
success: function (data) {
if (Object.keys(data).length > 0) {
//use data
}
$('#ajaxspinner').hide();
}
});
아약스 코드 전에 함수 내에서 스피너를 표시하고 있습니다.
$("#MyDropDownID").change(function () {
$('#ajaxspinner').show();
HTML의 경우 글꼴 멋진 클래스를 사용했습니다.
<i id="ajaxspinner" class="fas fa-spinner fa-spin fa-3x fa-fw" style="display:none"></i>
그것이 누군가를 돕기를 바랍니다.
당신은 항상 당신을 위해 모든 것을 수행하는 UI jQuery 플러그인 차단을 사용할 수 있으며, 아약스가로드되는 동안 모든 입력 페이지를 차단합니다. 플러그인이 작동하지 않는 것 같으면 이 답변에서 플러그인을 사용하는 올바른 방법에 대해 읽을 수 있습니다 . 확인 해봐.
참고 URL : https://stackoverflow.com/questions/68485/how-to-show-loading-spinner-in-jquery
'Programming' 카테고리의 다른 글
Android ListView 구분선의 색상을 변경하는 방법은 무엇입니까? (0) | 2020.02.22 |
---|---|
Git이 Subversion보다 나은 이유는 무엇입니까? (0) | 2020.02.22 |
android strings.xml에서 문자 및 문자를 작성하는 방법 (0) | 2020.02.22 |
pip 및 요구 사항 파일을 사용하여 특정 패키지를 업그레이드하려면 어떻게해야합니까? (0) | 2020.02.22 |
XML과 HTML을 정규식으로 구문 분석하기 어려운 이유에 대한 몇 가지 예를 제공 할 수 있습니까? (0) | 2020.02.22 |