jQueryでAJAXを利用するCodeigniterアプリを構築しています。私の見解の 1 つでは、次のように考えています。
ビュー/ユーザー/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');
}
});
}