私は、作業中のプロジェクトでたくさんのjQueryを使用しています。jsonでのエンコーディング応答の送信
JSONでデータを返すコントローラにajaxリクエストを送信するjavascript関数があります。
情報がまだ保存されていないことをユーザーに知らせるユーザーフレンドリーなメッセージを表示したいと考えています。しかし、JSONでレスポンスを送信する方法については混乱していますので、javascript関数はユーザーに表示する情報があるかどうかを判断できます。ここで
は私のjavascript関数である:
function latest_pheeds() {
var action = url+"pheeds/latest_pheeds";
$('#pheed-stream').html('<div class="loading"></div>');
$('.loading').append('<img src="'+pheed_loader_src+'" />');
$.ajax({
url:action,
type:'GET',
dataType:'json',
error: function() {
},
success:function(data) {
$('.loading').fadeOut('slow');
$.each(data,function(index,item) {
$('#pheed-stream').append
(
'<div class="pheed" id="'+item.pheed_id+'">'+
'<p><a class="user_trigger" href="users/info/'+item.user_id+'">'
+item.user_id+'</a></p>'+
'<p>'+item.pheed+'</p>'+
'<div class="pheed_meta">'+
'<span>'+item.datetime+' Ago</span>'+
'<span class="cm">'+item.comments+
'<img class="comment_trigger" src="/pheedbak/assets/img/comment.png" title="Click to comment on pheed" onclick="retrieve_comments('+item.pheed_id+')">'+
'</span>'+
'<span>'+item.repheeds+
' Repheeds'+
'<img class="repheed_trigger" src="/pheedbak/assets/img/communication.png" title="Click to repheed" onclick="repheed('+item.pheed_id+')">'+
'</span>'+
'<span>'+
'Favourite'+
'<img class="favourite_trigger" src="/pheedbak/assets/img/star.png" title="Click to make this a favourite" onclick="favourite_pheed('+item.pheed_id+')" />'+
'</span>'+
'</div>'+
'</div>'
);
});
}
});
}
そしてHERESにコントローラ機能のAjaxリクエストが
function latest_pheeds() {
//Confirm if a user is logged before allowing access
if($this->isLogged() == true) {
//load the pheed model for database interaction
$this->load->model('pheed_model');
//load user model
$this->load->model('user_model');
//load comment model
$this->load->model('comment_model');
//store the pheeds to a the $data variable
$data = $this->pheed_model->get_latest_pheeds();
//Load the date helper to calculate time difference between post time and current time
$this->load->helper('date');
//Current time(unix timetamp)
$time = time();
//pheeds
$pheeds = array();
if(count($data) > 0) {
foreach($data as $pheed) {
$row['pheed_id'] = $pheed->pheed_id;
$row['user_id'] = $this->user_model->return_username($pheed->user_id);
$row['pheed'] = $pheed->pheed;
$row['datetime'] = timespan($pheed->datetime,$time);
$row['comments'] = $this->comment_model->count_comments($pheed->pheed_id);
$row['repheeds'] = $pheed->repheeds;
$pheeds[] = $row;
}
echo json_encode($pheeds);
$response['response'] = "Ok";
$res[] = $response;
echo json_encode($res)."\n";
}
} else {
}
に行われることがJSON出力を生成しますが、私が読んカントような構文が壊れていますそれはjavacriptで、 しかし、私は上記のメソッドから次のコードを取り除くと正常に動作します。
$response['response'] = "Ok";
$res[] = $response;
echo json_encode($res)."\n";
iはHTTPヘッダの代わりに、WebページでのみJSONデータを送信することができますか? – Rajan