2016-07-01 38 views
0

我做了一個調用PHP的#container DIV在頁面中詢問的頁面的ajax腳本,所以如果我打電話project.html頁面,請求工作正常,調用頁面和$getscript相關但如果我嘗試打電話回來我的主頁的請求是重複的:Ajax請求重複頁回調

enter image description here

有我的PHP函數:

<?php $d="pages/" ; if(isset($_GET[ 'p'])){ $p=strtolower($_GET[ 'p']); if(preg_match("/^[a-z0-9\-]+$/",$p) && file_exists($d.$p. ".html")){ include $d.$p. ".html"; } else{ include $d. "404.html"; } } else{ include $d. "home.html"; } ?>

,這是我的Ajax請求:

var afficher = function(data, page) { 
 

 
    $('#container').fadeOut(500, function() { 
 
     $('#container').empty(); 
 
     $('#container').append(data); 
 
\t \t 
 
     $('#container').fadeIn(100, function() {}); 
 

 
    }); 
 
}; 
 

 
var loadPage = function(page, storeHistory) { 
 
    if (typeof storeHistory === 'undefined') { 
 
     storeHistory = true; 
 
    } 
 

 
    $.ajax({ 
 
     url: 'pages/' + page, 
 
     cache: false, 
 
     success: function(html) { 
 
      afficher(html, page); 
 
      if (storeHistory === true) { 
 
       history.pushState({ 
 
        'key': 'value', 
 
        'url': page 
 
       }, '', page); 
 
      } 
 
     }, 
 
     error: function(XMLHttpRequest, textStatus, errorThrown) { 
 
      afficher('erreur lors du chagement de la page'); 
 
     } 
 
    }); 
 

 
    return false; 
 
}; 
 

 
window.addEventListener('load', function() { 
 
    setTimeout(function() { 
 
     window.addEventListener('popstate', function(e) { 
 
      if (e.state === null) { 
 
       loadPage('home.html'); 
 
      } else { 
 
       loadPage(e['state']['url'], false); 
 
      } 
 
     }); 
 
    }, 0); 
 
}); 
 

 
$(document).ready(function() { 
 
\t $('.project a').on('click', function(e) { 
 
     var page = $(this).attr('href'); 
 
     loadPage(page); 
 
     return false; 
 
    }); 
 

 
\t $('#menu a').on('click', function() { 
 
     var page = $(this).attr('href'); 
 
     loadPage(page); 
 
     return false; 
 
    }); 
 
    
 
});

如何解決多個請求的問題,當我打電話給我的主頁?

回答

2

這裏的問題在某種程度上,事件一次又一次地增加。一個溫文爾雅的解決方案和建議的解決方案是在每次調用另一個ajax時放棄以前的ajax。所以它可以是:

var lastRequest = null; 
if(lastRequest!=null){ 
lastRequest.abort(); 
} 
lastRequest = $.ajax({ 
//your code 
    }); 

所以,通過這種方式,一次只會有一個活動的ajax。

希望有所幫助。

+0

那爲第一個ajax回調工作,但問題回來 – Tiaw

+0

即使在中止後也會出現問題嗎? –

+0

是的問題即將到來 – Tiaw