Codeigniter

CodeIgniter 에 적용하기 전에 매번 반복된는 XMLHttpRequest 객체를 사용하여 코드를 작성하기 번거롭기 때문에

해당 부분을 httpRequest.js 파일로 만들어 사용해보겠습니다.

 

httpRequest.js

 

function getXMLHttpRequest() {
	if (window.ActiveXObject) {
		try {
			return new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e1) { return null; }
		}
	} else if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else {
		return null;
	}
}
var httpRequest = null;

function sendRequest(url, params, callback, method) {
	httpRequest = getXMLHttpRequest();
	var httpMethod = method ? method : 'GET';
	if (httpMethod != 'GET' && httpMethod != 'POST') {
		httpMethod = 'GET';
	}
	var httpParams = (params == null || params == '') ? null : params;
	var httpUrl = url;
	if (httpMethod == 'GET' && httpParams != null) {
		httpUrl = httpUrl + "?" + httpParams;
	}
	httpRequest.open(httpMethod, httpUrl, true);
	httpRequest.setRequestHeader(
		'Content-Type', 'application/x-www-form-urlencoded');
	httpRequest.onreadystatechange = callback;
	httpRequest.send(httpMethod == 'POST' ? httpParams : null);
}

 

httpRequest.js 파일을 이용해 간단한 샘플을 만들어 보고 게시판 소스에 적용해보겠습니다.

Ajax 통신을 담당할 컨트롤러를 새로 만듭니다.

 

ajax_board.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Ajax 처리 controller.
 *
 * @author Jongwon, Byun <advisor@cikorea.net>
 */
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."님 반갑습니다!";
	}

 

 

ajax/test_v.php

 

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="apple-mobile-web-app-capable" content="yes" />
	<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no" />
	<title>CodeIgniter</title>
	<!--[if lt IE 9]>
	<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
	<script type="text/javascript" src="/bbs/include/js/httpRequest.js"></script>
	<script type="text/javascript">
	function server_request()
	{
		var csrf_token = getCookie('csrf_cookie_name');
		var name = "name="+encodeURIComponent(document.ajax_test.names.value)+"&csrf_test_name="+csrf_token;
		sendRequest("/bbs/ajax_board/ajax_action", name, callback_hello, "POST");
	}

	function callback_hello()
	{
		if ( httpRequest.readyState == 4 )
		{
			if ( httpRequest.status == 200 )
			{
				var contents = document.getElementById("contents");
				contents.innerHTML = httpRequest.responseText;
			}
		}
	}

	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>
</head>
<body>
<div id="main">
	<form method="post" name="ajax_test">
	<label>이름</label>
	<div>
		<input type="text" name="names" value="웅파">
	</div>

	<div>
		<input type="button" onclick="server_request()" value="전송">
	</div>
	</form>

	<div id="contents"></div>
</div>

</body>
</html>

 

 

CSRF 처리를 위해 config.php 설정 파일에서 해당 설정 값을 TRUE 로 설정했기 때문에 필요합니다.

csrf_coke_name 쿠키의 내용을 넘겨줘야 컨트롤러에서 정상적으로 처리합니다. 

만약, $config['csrf_protection'] 설정이 FALSE 라면 작성할 필요없습니다.

 

 

 

 

 

 

 

 

 

 

 

about author

PHRASE

Level 60  머나먼나라

잠이 오지 않을 때는 여름밤도 길고 피로한 자에게는 일리 길도 멀기만 하고 법(진리)을 구하지 않는 자에게는 만나기 어려운 인간 세상도 허무하기만 하느니. -법구경

댓글 ( 4)

댓글 남기기

작성