我正在構建一個利用AJAX和jQuery的Codeigniter應用程序。在我的意見之一,我有:主播通過AJAX調用ID
的意見/用戶/ index.php文件
<?php echo anchor('users/edit', 'Edit Profile', array(
'class' => 'user-link',
'id' => 'edit'
));?>
<?php echo anchor('users/private_messages', 'Private Messages', array(
'class' => 'user-link',
'id' => 'private_messages'
));?>
<div id="ajax-loader"><img src="<?php echo base_url();?>img/loading.gif"/></div>
<div id="result"></div>
<script type="text/javascript">
$(function(){
$('.user-link').click(function(event) {
event.preventDefault();
$.ajax({
url: $(this).attr('href'),
type: 'POST',
async: true,
beforeSend: function(){
$('#result').hide();
$('#ajax-loader').show();
},
error: function(xhr, status, thrown){
alert(xhr + ',' + status+ ',' + thrown);
},
complete: function(){
$('#ajax-loader').hide();
},
success: function(data) {
$('#result').empty().append(data);
$('#result').fadeIn('slow');
}
});
});
});
</script>
這工作得很好,它抓住每個錨的href
值並加載上點擊的方法。現在我想要做的是有訪問錨的的id
,例如加載與AJAX方法的能力,如果我訪問
http://appdomain.com/users/index#edit
我想抓住的是,href
值使用AJAX進行定位和調用。這背後的原因是,我有Edit
控制器指向users/index
內設置幾個重定向,我需要用AJAX刷新後再次調用該方法,所以我想是這樣的:
redirect(users/index#edit)
這是否實用?我需要一種在頁面加載時啓動對特定方法的AJAX調用的方法。任何建議將不勝感激。
編輯:
的JavaScript然後檢查它似乎工作拼搶哈希值:
var hash = window.location.hash;
var id = hash.substring(0);
if(id == '#edit' || id == '#private-messages'){
$.ajax({
url: $(id).attr('href'),
type: 'POST',
async: true,
beforeSend: function(){
$('#result').hide();
$('#ajax-loader').show();
},
error: function(xhr, status, thrown){
alert(xhr + ',' + status+ ',' + thrown);
},
complete: function(){
$('#ajax-loader').hide();
},
success: function(data) {
$('#result').empty().append(data);
$('#result').fadeIn('slow');
}
});
}
感謝您的建議,這很可能是正確的做法,如果我是加載與AJAX的所有方法,但是我只在我的兩個觀點中發送請求,所以我認爲我的方法(請參閱編輯)可能在小範圍內最實用。 – Dan