Codeigniter

 

 1. ajax 처리에서 반환 값으로 데이터를 파싱할 페이를 만든 후 반환하는   첫번째 방법 

 

 Ajax_board 

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax_board extends CI_Controller{

	function __construct()
	{
		parent::__construct();
	}
	
/*
	Ajax 테스트

*/
	public function test()
	{
		$this->load->view('ajax/test_v');
	}

	public function ajax_action()
	{
		echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
		$name=$this->input->post("name");
		echo $name."님 반갑습니다.!";
	}


	public function ajax_comment_add()
	{

		if(@$this->session->userdata('logged_in')==TRUE)
		{

			$this->load->model('board_m');

			$table=$this->input->post("table", TRUE);
			$board_pid=$this->input->post('board_id', TRUE);
			$comment_contents=$this->input->post('comment_contents', TRUE);


			if($comment_contents !='')
			{
				
				$write_data=array(
					'table' => $table, //게시판 테이블명
					'board_pid'=>$board_pid, //원글 번호
					'subject'=>'',
					'contents'=>$comment_contents,
					'user_id'=>$this->session->userdata('username')
				);

				//echo  implode(',' ,$write_data);
			
				$result =$this->board_m->insert_comment($write_data);

				if($result)
				{
					
					//글 작성 성공 시 댓글 목록 만들어 화면 출력
					$sql= " select * FROM ci_board  where board_pid = ? order by board_id desc ";
					$query=$this->db->query($sql , array(
						'0' => $board_pid
						)
					);

					//$data=$query->result();

					//echo json_encode($data);  1개의 데이터
					//echo json_encode($data);
					$data['comment']=$query->result();
					$this->load->view('board/ajax_commment_v', $data);
				
				}
				else
				{
					//글 실 패시 
					echo "글 작성에 실패 하였습니다.";
				}


			}
			else
			{
				//글 내용이 없을 경우
				echo "댓글 내용을 입력하세요.";
			}

		}
		else
		{
			//로그인 필요 에러
			echo "로그인하여야 합니다.";
			
		}
	}

}
 

 

다음 과 같이 ajax_comment_v.php 페이지를 만들어 데이터를  넘긴다.

ajax 에서 성공시 ajax_comment_v.php 페이지를 가져와서  html(ajax_comment_v.php데이터 ) 로 데이터를 넘겨 뿌려준다.

 

 ajax_comment_v.php


<table cellpadding="0" cellspacing="0" class="table table-striped">
	<tbody>
		
	<?php
		foreach ($comment  as $lt) {
	?>
	
		<tr>
			<th scope="row">
				<?php  echo $lt->user_id; ?>
			</th>

			<td><?php echo $lt->contents; ?></td>
			
			<td><?php  echo $lt->reg_date; ?></td>

			<td><a href="">삭제</a></td>
		</tr>

	<?php
		}
	?>
	</tbody>
</table>

 

 

view_v.php

		<form class="form-horizontal" method="post" action="/todo/board/write" name="com_add">
		  <fieldset>
		    <div class="control-group">
		      <label class="control-label" for="input01">댓글</label>
		      <div class="controls">
		        <textarea class="input-xlarge" id="input01" name="comment_contents" rows="3"></textarea>
				<input class="btn btn-primary" type="button" id="comment_add" value="작성">
		        <p class="help-block"></p>
		      </div>
		    </div>
		  </fieldset>
		</form>



		<div id="comment_area">
			<table cellspacing="0" cellpadding="0" class="table table-striped" id="comment_table">
			
			<?php
				foreach ($comment_list as $lt) {
			
			?>
				<tr id="row_num_<?php echo $lt->board_id; ?>">
					<th scope="row">
						<?php echo $lt->user_id; ?>
					</th>
					<td><?php echo $lt->contents;?></a></td>
					<td><?php echo $lt->reg_date; ?></td>
					<td>
					<a href="#" onclick="javascript:comment_delete('<?php  echo $lt->board_id; ?>')"><i class="icon-trash"></i>삭제</a></td>
				</tr>
			<?php			
				}
			?>
			</table>
		</div>

	</article>

<script type="text/javascript">
$(function(){

	$("#comment_add").click(function(){

		var comment_contents=encodeURIComponent($("#input01").val()) ;
		var csrf_test_name=getCookie('csrf_cookie_name');
		var table ="ci_board";
		var board_id =<?php echo $this->uri->segment(3); ?>;
		console.log("comment_contents : " + comment_contents + " csrf_test_name : " +csrf_test_name + " table : " +table + " board_id : " + board_id);
		

		$.ajax({
			url: "/todo/ajax_board/ajax_comment_add",
			type:"POST",
			data:{
				"comment_contents" :comment_contents,
				"csrf_test_name" :csrf_test_name,
				"table":table,
				"board_id":board_id

			},
			dataType:"html",
			success:function(data, status){
				
				//1. 첫번째 방법 
				$("#comment_area").html(data);	
				//2.두번째 방법
				//onSuccess(data,status);

				$("#input01").val('');

			},
			error:function(xhr){
				alert("댓글 에러");
			}

		});

	});



});

function getCookie( name )
	{
		var nameOfCookie = name + "=";
		var x = 0;

		while ( x <= document.cookie.length )
		{
			var y = (x+nameOfCookie.length);

			if ( document.cookie.substring( x, y ) == nameOfCookie ) {
				if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
					endOfCookie = document.cookie.length;

				return unescape( document.cookie.substring( y, endOfCookie ) );
			}

			x = document.cookie.indexOf( " ", x ) + 1;

			if ( x == 0 )

			break;
		}

		return "";
	}



	
</script>



codeIgniter CSRF ajax 처리시  getCookie 함수를 사용해서 처리한다.

다음 함수 값만 있으면 된다.

var csrf_test_name=getCookie('csrf_cookie_name');

 


function getCookie( name )
	{
		var nameOfCookie = name + "=";
		var x = 0;

		while ( x <= document.cookie.length )
		{
			var y = (x+nameOfCookie.length);

			if ( document.cookie.substring( x, y ) == nameOfCookie ) {
				if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
					endOfCookie = document.cookie.length;

				return unescape( document.cookie.substring( y, endOfCookie ) );
			}

			x = document.cookie.indexOf( " ", x ) + 1;

			if ( x == 0 )

			break;
		}

		return "";
	}

 

 

 

2. 두번째 방법  데이터 1개를  json  리턴 한 후 prepend 로 붙이는 방법

 

만약 88 번 레코드만 가져온다면 

$query->result() 를 jsson_encode 처리 한다.

if($result)
				{
					
					//글 작성 성공 시 댓글 목록 만들어 화면 출력
					$sql= " select * FROM ci_board  where board_pid = 88 order by board_id desc ";
					$query=$this->db->query($sql , array(
						'0' => $board_pid
						)
					);

					$data=$query->result();

					echo json_encode($data); // 1개의 데이터
					//echo json_encode($data);
					//$data['comment']=$query->result();
					//$this->load->view('board/ajax_commment_v', $data);
				
				}




function onSuccess(data2, status){
	console.log(data2);
	var answerTemplate =$("#answerTemplate").html();
	var data =JSON.parse(data2);
	
	console.log("json 길이 : " +data.length);
	console.log(" json  - " + data[0].user_id +" : " +  data[0].contents + " : "+  data[0].reg_date);
	var template =answerTemplate.format(data[0].user_id, data[0].contents,  data[0].reg_date);


	$("#comment_area").prepend(template);
}

 

 

템를릿 파싱  tring.prototype.format = function() 사용해서  데이터를 {0 }, ~ {끝} 까지 파싱한다.

이때 데이터 값은 json 값이 아니라  실질적인 데이터 값이다.

 

1. 자바스크립트 함수 코딩 :

 

String.prototype.format = function() {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{'+i+'\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
}

 

2. 템플릿에서 {0} ~ 순서대로 넣으주면 된다.

<script type="text/template" id="answerTemplate">

		<tr>
			<th scope="row">
				{0}
			</th>

			<td>{1}</td>
			
			<td>{2}</td>

			<td><a href="">삭제</a></td>
		</tr>

</script>

 

3. 데이터 삽입 처리 방법

 

var answerTemplate =$("#answerTemplate").html();

template +=answerTemplate.format(data[i].user_id, data[i].contents,  data[i].reg_date);

$("#comment_area").html(template);

 

 

 

위 처리만 하면 된다. 특별한 라이브러리 삽입은 없다.

 

 

 

 

3. 세번째 방법  리스트 데이터를  json 으로 encoding 한후 for 문으로 돌려 html 로 붙이는 방법


 

function onSuccess2(data2, status){
	console.log(data2);
	var answerTemplate =$("#answerTemplate").html();
	var data =JSON.parse(data2);

	var template='<table cellspacing="0" cellpadding="0" class="table table-striped" id="comment_table">';
	for(var i=0; i< data.length; i++){
	  template +=answerTemplate.format(data[i].user_id, data[i].contents,  data[i].reg_date);		  
	}
	template +="</table>";
	$("#comment_area").html(template);
}

 

 

전체 view_v.php  코드 

	


	<article id="board_area">
		<header>
			<h1></h1>
		</header>
		<table cellspacing="0" cellpadding="0" class="table table-striped">
			<thead>
				<tr>
					<th scope="col"><?php echo $views->subject;?></th>
					<th scope="col">이름 : <?php echo $views->user_name;?></th>
					<th scope="col">조회수 : <?php echo $views->hits;?></th>
					<th scope="col">등록일 : <?php echo $views->reg_date;?></th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<th colspan="4">
						<?php echo $views->contents;?>
					</th>
				</tr>
			</tbody>
			<tfoot>
				<tr>
					<th colspan="4"><a href="/todo/board/lists/<?php echo $this->uri->segment(3);?>/page/<?php echo $this->uri->segment(7);?>" class="btn btn-primary">목록</a> 
					<a href="/todo/board/modify/board_id/<?php echo $this->uri->segment(3);?>/<?php echo $this->uri->segment(4);?>page/<?php echo $this->uri->segment(6);?>" class="btn btn-warning">수정</a> 

<a href="/todo/board/delete/board_id/<?php echo $this->uri->segment(3);?>/<?php echo $this->uri->segment(4);?>/page/<?php echo $this->uri->segment(6);?>" class="btn btn-danger">삭제</a> 

				 <a href="/todo/board/write/<?php echo $this->uri->segment(3);?>/page/<?php echo $this->uri->segment(7);?>" class="btn btn-success">쓰기</a></th>
				</tr>
			</tfoot>
		</table>

		<form class="form-horizontal" method="post" action="/todo/board/write" name="com_add">
		  <fieldset>
		    <div class="control-group">
		      <label class="control-label" for="input01">댓글</label>
		      <div class="controls">
		        <textarea class="input-xlarge" id="input01" name="comment_contents" rows="3"></textarea>
				<input class="btn btn-primary" type="button" id="comment_add" value="작성">
		        <p class="help-block"></p>
		      </div>
		    </div>
		  </fieldset>
		</form>



		<div id="comment_area">
			<table cellspacing="0" cellpadding="0" class="table table-striped" id="comment_table">
			
			<?php
				foreach ($comment_list as $lt) {
			
			?>
				<tr id="row_num_<?php echo $lt->board_id; ?>">
					<th scope="row">
						<?php echo $lt->user_id; ?>
					</th>
					<td><?php echo $lt->contents;?></a></td>
					<td><?php echo $lt->reg_date; ?></td>
					<td>
					<a href="#" onclick="javascript:comment_delete('<?php  echo $lt->board_id; ?>')"><i class="icon-trash"></i>삭제</a></td>
				</tr>
			<?php			
				}
			?>
			</table>
		</div>

	</article>



<script type="text/template" id="answerTemplate">

		<tr>
			<th scope="row">
				{0}
			</th>

			<td>{1}</td>
			
			<td>{2}</td>

			<td><a href="">삭제</a></td>
		</tr>

</script>











<script type="text/javascript">
$(function(){

	$("#comment_add").click(function(){

		var comment_contents=encodeURIComponent($("#input01").val()) ;
		var csrf_test_name=getCookie('csrf_cookie_name');
		var table ="ci_board";
		var board_id =<?php echo $this->uri->segment(3); ?>;
		console.log("comment_contents : " + comment_contents + " csrf_test_name : " +csrf_test_name + " table : " +table + " board_id : " + board_id);
		

		$.ajax({
			url: "/todo/ajax_board/ajax_comment_add",
			type:"POST",
			data:{
				"comment_contents" :comment_contents,
				"csrf_test_name" :csrf_test_name,
				"table":table,
				"board_id":board_id

			},
			dataType:"html",
			success:function(data, status){
				
				//1. 첫번째 방법 
				//$("#comment_area").html(data);	
				//2.두번째 방법
				onSuccess(data,status);

				$("#input01").val('');

			},
			error:function(xhr){
				alert("댓글 에러");
			}

		});

	});



});

function getCookie( name )
	{
		var nameOfCookie = name + "=";
		var x = 0;

		while ( x <= document.cookie.length )
		{
			var y = (x+nameOfCookie.length);

			if ( document.cookie.substring( x, y ) == nameOfCookie ) {
				if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
					endOfCookie = document.cookie.length;

				return unescape( document.cookie.substring( y, endOfCookie ) );
			}

			x = document.cookie.indexOf( " ", x ) + 1;

			if ( x == 0 )

			break;
		}

		return "";
	}




function onSuccess(data2, status){
	console.log(data2);
	var answerTemplate =$("#answerTemplate").html();
	var data =JSON.parse(data2);
	
	console.log("json 길이 : " +data.length);
	console.log(" json  - " + data[0].user_id +" : " +  data[0].contents + " : "+  data[0].reg_date);
	var template =answerTemplate.format(data[0].user_id, data[0].contents,  data[0].reg_date);


	$("#comment_area").prepend(template);
}




function onSuccess2(data2, status){
	console.log(data2);
	var answerTemplate =$("#answerTemplate").html();
	var data =JSON.parse(data2);

	var template='<table cellspacing="0" cellpadding="0" class="table table-striped" id="comment_table">';
	for(var i=0; i< data.length; i++){
	  template +=answerTemplate.format(data[i].user_id, data[i].contents,  data[i].reg_date);		  
	}
	template +="</table>";
	$("#comment_area").html(template);
}


String.prototype.format = function() {
    var formatted = this;
    for (var i = 0; i < arguments.length; i++) {
        var regexp = new RegExp('\\{'+i+'\\}', 'gi');
        formatted = formatted.replace(regexp, arguments[i]);
    }
    return formatted;
}		
</script>

 

 

 

about author

PHRASE

Level 60  머나먼나라

훌륭한 사상은 역시 훌륭한 인격에 담긴다. 작은 그릇에는 작은 음식밖에 담기지 않듯이 인격이 작고서는 큰 사상이 담길 도리가 없다. 작으나 크나 사상은 그 사람의 인격을 토대로 세워진 하나의 건축물이다. -알랭

댓글 ( 0)

댓글 남기기

작성