1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>배열/객체의 내용을 순서대로 처리하기</title> </head> <body> <ul id="list"></ul> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> $(function() { var animal = [ { name: '프렌치불독', type: '강아지'}, { name: '요크셔테리어', type: '강아지'}, { name: '닥스훈트', type: '강아지'}, { name: '스코티시폴드', type: '고양이'}, { name: '포메라니안', type: '강아지'}, ]; $.each( animal, function(index, value) { // '고양이'가 발견되면 출력을 중지 if(value.type == '고양이') { return false; } $('<li></li>') .append(value.name) .appendTo('#list'); } ); }); </script> </body> </html> |
2018년 6월 21일 목요일
[JavaScript 예제] 065 배열/객체의 내용을 순서대로 처리하기
2018년 6월 20일 수요일
[JavaScript 예제] 064 해시/객체들 병합하기
객체/해시(연관 배열)를 결합하려면 jQuery의 $.extend 메소드를 이용한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>해시/객체들 병합하기</title> </head> <body> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> var data1 = { id:10, name:'Ava' } var data2 = { age:40, married:true } var data3 = { blood:'A', name:'David' } $.extend(data1, data2, data3); console.log(data1); // 결과: {id: 10, name: "David", age: 40, married: true, blood: "A"} </script> </body> </html> |
같은 이름 멤버가 존재하는 경우 나중의 것으로 덮어쓴다.
- 위의 경우에서 data1의 내용을 변경하지 않을려면 다음과 같이 한다.
- var merged = $.extend({}, data1, data2, data3);
[JavaScript 예제] 062 배열 가지고 놀기
배열의 요소를 추가/삭제
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>배열 가지고 놀기</title> </head> <body> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> var data = ['팬더', '토끼', '코알라']; data.push('땅콩'); data.unshift('강아지'); console.log(data.toString()); // 결과: 강아지,팬더,토끼,코알라,땅콩 console.log(data.pop()); // 결과: 땅콩 console.log(data.toString()); // 결과: 강아지,팬더,토끼,코알라 console.log(data.shift()); // 결과: 강아지 console.log(data.toString()); // 결과: 팬더,토끼,코알라 </script> </body> </html> |
- push() / pop() 메소드
- 배열의 끝 요소를 넣고 뺀다
- unshift() / shift() 메소드
- 배열의 첫 요소를 넣고 뺀다
배열에 배열을 연결하기 ( concat() 메소드 )
배열 결합 ( 배열.join([구분문자]) )
배열 일부 빼내기 ( 배열.slice(시작위치 [,종료위치]) )
배열의 내용 치환하기 ( 배열.splice(시작위치, 요소수 [, 치환후의요소, ...] )
배열의 요소 정렬하기
- 배열.sort(function(m, n) {
...정렬규칙...
})
2018년 6월 12일 화요일
[JavaScript 예제] 055 정규 표현 사용
| 분류 | 패턴 | 매칭하는 문자열 |
| 기본 | xyz | 'xyz'라는 문자열 |
| [xyz] | x, y, z 중 1개의 문자 | |
| [^xyz] | x, y, z 이외의 1개의 문자 | |
| [a-z] | a~z 사이의 1개의 문자 | |
| x|y|z | x, y, z 중 하나 | |
| 양 지정 | x* | 0문자 이상의 x("to*"는 "t", "to", "too" 등에 일치) |
| x? | 0또는 1문자의 x("to?"는 "t", "to"에 일치) | |
| x+ | 1문자 이상의 x("to+"는 "to", "too" 등에 일치) | |
| x{n} | x와 n회 일치("[0-9]{4}"는 4자리 숫자) | |
| x{n,} | x와 n회 이상 일치("[0-9]{4,}"는 4자리 이상의 숫자) | |
| x{m,n} | x와 m~n회의 일치("[0-9]{2,4}"는 2~4자리 숫자) | |
| 위치 지정 | ^ | 앞부분이 일치 |
| $ | 끝부분이 일치 | |
| 문자 세트 | . | 임의의 1문자에 일치 |
| \w | 대문자/소문자의 영문자, 숫자, 언더스코어(_)에 일치 ("[A-Za-z0-9_]"와 동일) |
|
| \W | 문자 이외에 일치("[^\w]"와 동일) | |
| \d | 숫자에 일치("[0-9]"와 동일) | |
| \D | 숫자 이외에 일치("[^0-9]"와 동일 | |
| \n | 개행(라인 피드)에 일치 | |
| \r | 복귀(캐리지 리턴)에 일치 | |
| \f | 폼피드에 일치 | |
| \t | 탭 문자에 일치 | |
| \v | 수직 탭에 일치 | |
| \s | 공백 문자에 일치("[\n\r\t\v\f]"와 동일) | |
| \S | 공배 이외의 문자에 일치("[^\s]"와 동일) | |
| \~ | '~'에서 나타내는 문자 |
JavaScript에서 이들의 정규 표현식 패턴을 해석하고 검색 등 기능을 제공하는 것은 RegExp 객체의 역할이다.
- RegExp 생성자
- var 변수 = new RegExp(정규표현, 옵션)
- 정규 표현 리터럴
- var 변수 = /정규 표현/옵션
- 정규 표현식 옵션
- g
- 문자열 전체에 매치하는가
- i
- 대문자/소문자의 구분을 무시하는가
- m
- 개행 코드를 행 첫머리/행의 끝으로 인식하는가(여러행일 경우)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>정규 표현</title> </head> <body> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> // test 메소드 var ex = /http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/gi; var str1 = '샘플 파일은 http://www.Infopub.co.kr/에서 다운로드 할 수 있음'; var str2 = '질문은 "게시판"으로 부탁드림'; console.log(ex.test(str1)); // 결과 : true console.log(ex.test(str2)); // 결과 : false // search 메소드 console.log(str1.search(ex)); // 결과 : 7 console.log(str2.search(ex)); // 결과 : -1 // match var str = str1; str += '질문은 HTTP://www.infopub.co.kr/로 부탁함'; var result = str.match(ex); for(var i=0, len = result.length; i<len; i++) { console.log(result[i]); } // 결과 // http://www.Infopub.co.kr/ // HTTP://www.infopub.co.kr/ // 정규 표현으로 문자열 치환 var ex1 = /(http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?)/gi; console.log(str1.replace(ex1, '<a href="$1">$1</a>')); // 결과 : 샘플 파일은 <a href="http://www.Infopub.co.kr/">http://www.Infopub.co.kr/</a>에서 다운로드 할 수 있음 // 정규 표현으로 문자열 문할 var ex2 = /[\s\n\t]/gi; console.log('JavaScript Project'.split(ex2)); // 결과 : (2) ["JavaScript", "Project"] console.log('JS\n커뮤니티'.split(ex2)); // 결과 : (2) ["JS", "커뮤니티"] console.log('JS Power프로젝트'.split(ex2)); // 결과 : (7) ["JS", "", "", "", "", "", "Power프로젝트"] </script> </body> </html> |
2018년 6월 11일 월요일
[JavaScript 예제] 045 반올림 & n진수 구하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>반올림</title> </head> <body> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> // 소수점 이하 수치 반올림하기 console.log(Math.ceil(4.56)); // 결과 : 5 console.log(Math.ceil(-4.56)); // 결과 : -4 console.log(Math.floor(4.56)); // 결과 : 4 console.log(Math.floor(-4.56)); // 결과 : -5 console.log(Math.round(4.56)); // 결과 : 5 console.log(Math.round(-4.56)); // 결과 : -5 // 임의의 자릿수에서 소수점을 반올림하기 var num = 123.456; console.log(num.toFixed(2)); // 결과 : 123.46 console.log(num.toFixed(5)); // 결과 : 123.45600 console.log(num.toPrecision(5)); // 결과 : 123.46 console.log(num.toPrecision(8)); // 결과 : 123.45600 // n진수 구하기 num = 255; console.log(num.toString(2)); // 결과 : 11111111 console.log(num.toString(16)); // 결과 : ff console.log(num.toString(36)); // 결과 : 73 </script> </body> </html> |
- 난수 구하기
- console.log(Math.floor((Math.random() * 100) + 1));
2018년 5월 29일 화요일
[JavaScript 예제] 044 계층을 가진 네임스페이스 정의하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>계층을 가진 네임스페이스 정의하기</title> </head> <body> <script> var namespace = function(ns) { // 네임스페이스를 '.'로 분할 var elems = ns.split('.'); var parent = window; // 이후 네임스페이스를 차례로 계층화하면서 등록 for(var i=0, len=elems.length; i<len; i++) { parent[elems[i]] = parent[elems[i]] || {}; parent = parent[elems[i]]; } return parent; }; // Myapp.Recipe.Samples 네임스페이스를 등록 var ns = namespace('Myapp.Recipe.Samples'); // 네임스페이스 예하에 클래스를 정의 ns.MyClass = function() {}; var c = new ns.MyClass(); console.log(c instanceof Myapp.Recipe.Samples.MyClass); // true </script> </body> </html> |
[JavaScript 예제] 043 클래스 이름 충돌 피하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>클래스 이름 충돌 피하기</title> </head> <body> <script> var Info = Info || {}; // Info가 비어 있는 경우에만 새로운 이름 공간을 작성 Info.Person = function(name, birth) { this.name = name; this.birth = birth; }; Info.Person.prototype.toString = function() { return this.name + ' _ _ ' + this.birth; } var p = new Info.Person('이정우', new Date(1981, 5, 16)); console.log(p.toString()); </script> </body> </html> |
[JavaScript 예제] 042 객체형 판정하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>객체형 판정하기</title> </head> <body> <script> var Person = function() {}; // 함수 선언 var BusinessPerson = function() {}; // 함수 선언 BusinessPerson.prototype = new Person(); // Person을 상속 var bp = new BusinessPerson(); // BusinessPerson 객체 생성 console.log(bp instanceof BusinessPerson); // 결과 true console.log(bp instanceof Person); // 결과 true console.log(bp instanceof Object); // 결과 true </script> </body> </html> |
2018년 5월 28일 월요일
[JavaScript 예제] 040 클래스 상속하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>클래스 상속하기</title> </head> <body> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> // 부모 클래스 Person var Person = function() {}; Person.prototype = { eat : function() {console.log('우물우물');} }; // Person 클래스를 상속한 BusinessPerson 클래스 var BusinessPerson = function() {}; BusinessPerson.prototype = new Person(); BusinessPerson.prototype.work = function() { console.log('먹보');} var bp = new BusinessPerson(); bp.eat(); bp.work(); </script> </body> </html> |
[JavaScript 예제] 037 클래스 정의하기
JavaScript에서 클래스르르 정의하려면 함수를 이용한다.
프로토타입 기반 객체 지향
주의
new 연산 없이 호출 경우
클래스에 메소드 추가하기
정적 멤버 추가하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>클래스 정의하기</title> </head> <body> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> var Animal = function(name) { this.name = name; this.toString = function() { return 'Animal:' + this.name; }; }; var ani = new Animal('바루'); console.log(ani.name); console.log(ani.toString()); </script> </body> </html> |
프로토타입 기반 객체 지향
- JavaScript는 객체 지향 언어이지만 그 구문은 프로토타입이라는 개념을 바탕으로 하고, 그 특수성을 말할 때 대표적인 특징으로 예를 든다.
- 일반적인 클래스 기반 객체 지향에 대하여 프로토타입 기반의 객체 지향이라고 한다
- 무엇보다 프로토타입 자체는 조금도 특수한 것이 아니라 '제약이 느슨한 클래스' 같은 것으로 인식하면 된다.
주의
- 이름은 대문자로 시작한다.
- 프로퍼티는 'this.프로퍼티 이름' 으로 정의한다.
- 메소드는 함수형 프로퍼티이다.
- 반환값은 필요 없다.
- 생성자에서 자동으로 this가 가리키는 객체를 돌려주기 때문에 반환값은 필요 없다.
- 명시적으로 반환값을 돌려준 경우 그 값이 new 연산자의 값이 된다.
- 이 경우 this에 대한 프로퍼티 설정 등은 무시되므로 주의
new 연산 없이 호출 경우
1 2 3 4 5 6 | var Animal = function(name) {
if(!(this instanceof Animal)) {
return new Animal(name);
}
// 코드 구성
}
|
클래스에 메소드 추가하기
생성자함수.prototype.메소드명 = function(...) {...}
정적 멤버 추가하기
생성자함수.프로퍼티명 = 값
생성자함수.메소드명 = function(...) {...}
[JavaScript 예제] 033 함수를 인수로서 전달하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>함수를 인수로서 전달하기</title> </head> <body> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> function benchmark(proc) { var start = new Date(); proc(); var end = new Date(); return end.getTime() - start.getTime(); } console.log( benchmark(function() { var x = 15; for(var i=0; i<10000000; i++) { x *= i; } }) ); </script> </body> </html> |
[JavaScript 예제] 028 함수 정의하기
함수 정의하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // function 명령
function getSquareArea(width, height) {
return width * height;
}
// Function 생성자
var getSquareArea = new Function(
'width', 'height', 'return width * height;');
// 함수 리터럴
var getSquareArea =
function(width, height) { return width * height; };
console.log(getSquareArea(2, 3));
|
인수의 기본값 설정하기
1 2 3 4 5 6 7 8 9 | function getSquareArea(o_width, o_height) {
if( o_width === undefined ) { o_width = 1; }
if( o_height=== undefined ) { o_height= 1; }
return o_width * o_height;
}
colsole.log(getSquareArea(10, 5));
colsole.log(getSquareArea(10));
colsole.log(getSquareArea());
|
필수 인수 확인하기
1 2 3 | if(width === undefined) {
throw { name: 'ArgsMissing', message: '폭이 지정되지 않았습니다.' };
}
|
값만 전달하는 인수와 명명된 인수
1 | showPanel('content.html', 200, 300, true, true, false);
|
1 2 3 4 5 6 7 8 | showPanel({
Path: 'content.html', // 패널로 표시하는 내용
height: 200, // 높이
width: 300, // 폭
resizable: true, // 리사이즈 가능여부
draggable: true, // 드래그 가능여부
modeless: false // 모달리스 패널여부
});
|
1 2 3 4 5 6 7 8 9 10 11 | function showPanel(args) {
if(args.path === undefined) {
throw { name: 'ArgsMissing', message: 'path는 필수임.' };
}
if(args.height === undefined) { args.height = 200; }
if(args.width === undefined) { args.width = 300; }
if(args.resizable === undefined) { args.resizable = true; }
if(args.draggable === undefined) { args.draggable = true; }
if(args.modeless === undefined) { args.modeless = false; }
// ..... 구현부분
}
|
가변 길이 인수를 갖는 함수정의
- 기본예
1 2 3 4 5 6 7 8 9 | function max(v_args) { var result = Number.NEGATIVE_INFINITY; for(var i=0, len=arguments.length; i<len; i++) { if(result < arguments[i]) { result = arguments[i]; } } return result; } |
- 고정인수와 가변 인수가 함께 있는 예
1 2 3 4 5 6 7 8 9 | function sprintf(format) { for(var i=1, len=arguments.length; i<len; i++) { var pattern = new RegExp('\\{' + (i-1) + '\\}', 'g'); format = format.replace(pattern, arguments[i]); } return format; } console.log(sprintf('{0}를 키우는데 이름은 {1}입니다.', '햄스터', '롤리')); |
2018년 5월 22일 화요일
[JavaScript 예제] 012 JavaScript 문법
배열
은 리터럴 표현으로 선언
var data2 = [ 'JavaScript', 'CoffeeScript', 'TypeScript' ];
data2[1]과 같이 사용
연관 배열
은 해시라고도 함, {}를 사용하여 생성
var obj1 = { a:100, b:500, c:800 };
obj1['a']와 같이 사용
데이터형 변환
parseInt()
parseFloat()
Number()
문자열형, 논리형으로 변환
typeof String(123); // String Type으로 변환 후 typeof에 의하여 string 결과
typeof Boolean(-1); // Boolean Type으로 변환 후 typeof에 의하여 Boolean 결과
console.log(typeof String(123)); // -> 결과 string
console.log(typeof new String(123)); // -> 결과 object
보다 쉽게 데이터형 변환
15 + ''; // -> string 형으로 변환
'15' - 0; // number 형으로 변환
!!value; // boolean형으로 변환
변수의 데이터형 판정
jQuery의 $.isXxxxx 메소드를 이용
지정된 변수의 형을 문자열로 봔환하는 $.type 메소드도 있다.
은 리터럴 표현으로 선언
var data2 = [ 'JavaScript', 'CoffeeScript', 'TypeScript' ];
data2[1]과 같이 사용
연관 배열
은 해시라고도 함, {}를 사용하여 생성
var obj1 = { a:100, b:500, c:800 };
obj1['a']와 같이 사용
데이터형 변환
parseInt()
parseFloat()
Number()
문자열형, 논리형으로 변환
typeof String(123); // String Type으로 변환 후 typeof에 의하여 string 결과
typeof Boolean(-1); // Boolean Type으로 변환 후 typeof에 의하여 Boolean 결과
console.log(typeof String(123)); // -> 결과 string
console.log(typeof new String(123)); // -> 결과 object
보다 쉽게 데이터형 변환
15 + ''; // -> string 형으로 변환
'15' - 0; // number 형으로 변환
!!value; // boolean형으로 변환
변수의 데이터형 판정
jQuery의 $.isXxxxx 메소드를 이용
| 메소드 | 개요 | 예와 결과 |
| isArray | 배열 여부 | $.isArray(['one', 'two']) <- true |
| isEmptyObject | 비어 있음 여부 | $.isEmptyObject({a: 'hi'}) <- false |
| isFunction | 함수 여부 | $.isFunction(123) <- false |
| isNumeric | 수치 여부 | $.isNumeric(123) <- true |
| isPlainObject | Object 객체 여부 | $.isPlainObject({a: 'hi'}) <- true |
| isWindow | Window 객체 여부 | $.isWindow(window) <- true |
| isXMLDoc | XML 문서 여부 | $.isXMLDoc($.parseXML('<name>infopub</name>')) <- true |
지정된 변수의 형을 문자열로 봔환하는 $.type 메소드도 있다.
[JavaScript 예제] 008 문자열 표시하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>문자열 표시하기</title> </head> <body> <div id="result"></div> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> var str1 = '안녕, 문자열1'; var str2 = "안녕, 문자열2"; // 대화상자를 표시 window.alert(str1); // 콘솔에 표시 console.log(str2); // 페이지(id="result")에 있는 요소에 직접 표시 $('#result').text(str2); // 페이지 상에 출력 document.write(str1); </script> </body> </html> |
주요 이스케이프 시퀀스
| 이스케이프 시퀀스 | 설명 |
|---|---|
| \b | 백스페이스 |
| \t | 탭 |
| \n | 개행 |
| \f | 페이지 열기 |
| \r | 복귀 |
| \' | 작은 따옴표 |
| \" | 큰 따옴표 |
| \\ | \문자 |
| \xXX | XX(2자리 16진수)로 나타내는 Latin-1 문자 |
| \uXXXX | XXXX(4자리 16진수)로 나타내는 Unicode 문자 |
[JavaScript 예제] 006 JavaScript 코드 압축하기
온라인에서 이용할 수 있는 압축 도구
http://javascriptcompressor.com/
오프라인에서 이용할 수 있는 압축도구
https://archive.codeplex.com/?p=aspnet
http://javascriptcompressor.com/
오프라인에서 이용할 수 있는 압축도구
https://archive.codeplex.com/?p=aspnet
[JavaScript 예제] 005 JavaScript의 위험한 구문 제거하기
Strict 모드를 이용한다.
Strict 모드는 '구문으로 존재하지만, 안전성/효율성의 관점에서 이용해서는 안 되는 것'을 검출하여 에러를 발생시키는 모드이다.
Strict 모드의 주요 제한
함수에서 strict 모드 사용 방법
Strict 모드의 대응 브라우저
Strict 모드는 '구문으로 존재하지만, 안전성/효율성의 관점에서 이용해서는 안 되는 것'을 검출하여 에러를 발생시키는 모드이다.
Strict 모드의 주요 제한
| 분류 | 제한 내용 |
|---|---|
| 변수 | var 명령은 생략할 수 없다. 매개변수/속성 이름의 중복 금지 undefined, NaN으로 대입 금지 |
| 명령 | with 명령은 이용할 수 없다 arguments, callee 속성에 접근할 수 없다 eval 명령으로 선언된 변수를 주위의 범위에 확산하지 않는다 |
| 기타 | 함수 아래 this는 Global 객체를 나타내지 않는다(undefined이 된다) '0~'(8진수 표기)는 불가 |
함수에서 strict 모드 사용 방법
1 2 3 4 | function sample() {
'use strict';
// 함수의 본체
}
|
Strict 모드의 대응 브라우저
| 브라우저 | 대응 버전 |
|---|---|
| Internet Explorer | 10~ |
| Chrome | 13~ |
| Firefox | 4~ |
| Safari | 6~ |
| Opera | 11.6~ |
[JavaScript 예제] 001 HTML 페이지에 JavaScript 코드 사용하기
- <script> 요소를 이용하기
1 2 3 4 5 6 7 8 9 10 11 12 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>HTML 페이지에 JavaScript 코드 사용하기</title> </head> <body> <script type="text/javascript"> console.log('Wooguy javascript 입니다.'); // 로그 출력 확인은 F12키 </script> </body> </html> |
- 외부 스크립트를 임포트하기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>HTML 페이지에 JavaScript 코드 사용하기</title> </head> <body> <p>Smart Link 프로젝트에서는 현재<span id="mem">멤버 모집 중</span>입니다.</p> <!--외부 스크립트--> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <!--인라인 스크립트--> <script type="text/javascript"> $(function() { $('#mem').css('background-color', '#ff6'); }); </script> </body> </html> |
- 문자 코드는 UTF-8을 권장
[PHP예제] 237 JSON 형식의 데이터를 반환하는 Web API 만들기
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php if( !isset($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] !== 'XMLHttpRequest' ) { die(json_encode(array('status' => "잘못된 호출입니다."))); } // 데이터를 준비 $value = array( 1 => array('item' => '라면', 'price' => 580, 'orders' => 113), 2 => array('item' => '라면(아메리칸)', 'price' => 580, 'orders' => 72), 3 => array('item' => '볶음밥', 'price' => 630, 'orders' => 87), ); header("Content-Type: application/json; charset=UTF-8"); // IE가 Content-Type 헤더를 무시하지 않게 함 header('X-Content-Type-Optoins: nosniff'); echo json_encode( $value, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP ); |
[PHP예제] 235 다른 페이지로 건너뜀
1 2 3 4 | <?php header('HTTP/1.1 303 See Other'); header('Location: http://www.woorits.com/'); exit(); |
http://www.woorits.com 사이트로 강제 이동
[PHP예제] 231 강제로 파일 다운로드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php $fileName = 'test.jpg'; $fileSize = filesize($fileName); $mime = 'image/jpeg'; //$mime = 'application/octet-stream'; // MIME 타입이 불분명한 경우 header('Content-Type: ' . $mime); // IE가 Content-Type 헤더를 무시하지 않게 함 header('X-Content-Type-Optoins: nosniff'); header('Content-Disposition: attachment; filename="' . $fileName . '"'); header('Content-Transfer-Encoding: binary'); header('Cache-Control: no-store, no-cache, must-revalidate'); if( isset($_SERVER['HTTP_USER_AGENT']) && strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') ) { header('Cache-Control: post-check=0, pre-check=0', false); header('pragma: public'); } header('Content-Length: ' . $fileSize); readfile($fileName); |
test.jpg 파일이 다운로드 됨
피드 구독하기:
글 (Atom)


