함수

javascript 2023. 3. 27. 20:44

function a() { } 보다 ,    const a = () => {} 로 쓰는게 좋다.

==> 이유 1. function은 생성자인지 함수용도인지 헤깔리지만, const는 항상 함수 용도이다.  생성자가 필요하면 class로 쓰면 된다.

         이유 2. const의 우측 ()=>{} 이걸 변수에 대입하는 느낌으로 array안 이나, 함수 parameter등 동일한 방식으로 사용가능하단.

단,

let object= {

    name: 'kim'

    run : ()=> {}   까지는 굿인데, {}안에서 this는 못 쓰는 문제가 있어, 이때는 function써도 되지만 위 문제들 때문에 그냥
    run() {..}        쓰면 된다.

}

 

 

closure: 내부함수가 외부함수의 변수를 access할 수 있다. (상식수준임) =>  예제코드에선 function이 이너함수를 리턴하는 형태가 많음.

 

Javascript map과 forEach의 차이점.  map은 매번 뭔가를 리턴을 한다. 따라서 array를 map시 새 array가 생긴다.

 

[ CSS 로 이동예정]

CSS specicificity:  인라인 style1순위, ID 2순위, class 3순위, 요소 4순위 => 1,0,0,0 혹은 1000 형태로 표현됨. 0010 은 class임.

 =>  p { color:red;]  .p1 { color:green; } 이면  p는 0.0.0.2 이고  .p1은 0.0.1.0 이라서  .p1이 힘이 우선 적용된다...

   (p가 0.0.0.1이 아니고 0.0.0.2인 이유는 아직 잘 모르겠음)

 

 

 

Posted by yongary
,

spread ...

javascript 2023. 3. 21. 00:00

1. let arr = [ [1,2], [2,3] ]

...arr 은  [1,2], [2,3] 을 의미하지만 직접 사용하지는 못하고 [...arr]이나 {...arr} 등으로 사용가능하다.

 

2. let json = {a:1, b:2}

 ...json 은 a:1, b:2 를 의미하지만 위 예제와는 달리 iterable은 아니라서   {...json}형태로 쓰면 복사효과가 있다.

 

 

1에서 let spread = [].concat( ...arr)
  ==>  spread 는  [1, 2, 2, 3] 이 된다. concat이 여러개 array(iterable)를 수용가능.

 

 

Posted by yongary
,

1. char -> AsciiCode
   'A'.charCodeAt()  => 65  ,    'AB'.charCodeAt(1) => 66

 

2. AsciiCode -> char
   String.fromCharCode(65) => 'A'

 

 

 

 

//Ascii를 이용한 간단한 암호화 알고리듬. 

function encrypt(str) {   //입력이 length=7자리 정도는 된다고 보면  'ABCDEFG'

    //ascii값에 (index+1)더하기.   A+1, B+2, C+3..  G+7

   let rotatedStr = '';

   for (let i = 0; i < str.length; i ++) {
          rotatedStr = rotatedStr + String.fromCharCode(str.charCodeAt(i) + ( i +1 ))
   } 
    
   //로테이션 시키고    //중간에 양념넣기
   let tempStr = '0xe0' + rotatedStr.substring(3) + 'T2n0' + rotatedStr.substring(0,3);  //(4) + 4 + (4) +[3] : DEFG + TEMP + ABC

   return tempStr;

}


function decrypt(tempStr) {  //length:11  

  //양념빼면서 로테이션 해제  //3+4로 복귀

  let rotatedStr = tempStr.substring(tempStr.length - 3) + tempStr.substring(4, tempStr.length-7 )  //뒤 + 앞. 

   

  let str = '';
  for (let i = 0; i < rotatedStr.length; i ++) {
          str = str + String.fromCharCode(rotatedStr.charCodeAt(i) - ( i +1 ));
  } 

  return str;

}

 

Posted by yongary
,

js HashMap 정수용

javascript 2018. 4. 16. 17:40

예전에는 아래 방식이 좋다고 생각했었는데,

최근엔 그냥 json을 hashMap으로 써도 충분한것 같다. (좀 늦으려나?)

 

let hm = {}

hm['key1']  = 2

hm['key2'] = 3

 

==> 이렇게 하면 바로 hashMap처럼 사용가능.  hm = {key1:2, key2:3} 이며, 이렇게 저장해도 됨.

 

--------------- 아래 --------------

REF 를 수정해서 만듦.

<javascript용 정수를 자동 add해주는 HashMap>

 

Map = function(){

 this.map = new Object();

};   

Map.prototype = {   

    put : function(key, value){   

 if (typeof this.get(key) == 'undefined')

             this.map[key] = value;

       else

 this.map[key] = this.map[key]+value;

    },   

    get : function(key){   

        return this.map[key];

    },

   

    //밑에 함수들은 사실 별필요 없음, 검증도 필요하고..

    containsKey : function(key){    

     return key in this.map;

    },

    containsValue : function(value){    

     for(var prop in this.map){

      if(this.map[prop] == value) return true;

     }

     return false;

    },

    isEmpty : function(key){    

     return (this.size() == 0);

    },

    clear : function(){   

     for(var prop in this.map){

      delete this.map[prop];

     }

    },

    remove : function(key){    

     delete this.map[key];

    },

    keys : function(){   

        var keys = new Array();   

        for(var prop in this.map){   

            keys.push(prop);

        }   

        return keys;

    },

    values : function(){   

     var values = new Array();   

        for(var prop in this.map){   

         values.push(this.map[prop]);

        }   

        return values;

    },

    size : function(){

      var count = 0;

      for (var prop in this.map) {

        count++;

      }

      return count;

    }

};

 

var map = new Map();

map.put("ag", 5);

map.put("ag", 2);

map.get("ag");  ===> 7

Posted by yongary
,

gulp & webpack & lodash

javascript 2017. 8. 21. 16:21

<gulp>

gulp는 빌드 및  dependency관리 툴이다. Node.js의 스트림기능을 이용한 streaming build System을 표방한다.  REF

 - gulp.task
 - gulp.src
 - gulp.dest
 - gulp.watch 

gulpfile.js 을 작성해서, plugin사용을 통해 html/css/js/image 등을 minify 한다.

sass 를 css로 컴파일 하는 기능도 수행.



<webpack> 

모듈쪼개기(번들러) 툴이다. 모듈간 import/include를 지원한다.   (javascript ES6에도 모듈이 있어 약간 쪼개기 가능) 
                                                                                                - REF:      import './style.sass';

webpack.config.js를 통해서 설정을 함. REF
  - entry 
  - CommonChunkPlugin을 통해 split함..
  (+inline  function)

- webpack-dev-server : 간단한 webserver 제공. REF

- webpack-stream: 주로 babel인데 gulp랑 함께 사용? (need to study)
  
  

- webpack-dev-middleware  (webpack-dev-server내부에서 사용)

- webpack Watch Mode : js가 하나라도 바뀌면 재컴파일.



<lodash>

그냥 js 라이브러리이다.  arrays, collections,  numbers, objects, strings 등을 유려하게 처리한다.  REF

_.every
_.filter
_.find  
_.forEach
_.includes
_.map 
_.reduce 






Posted by yongary
,

package.json안에서 사용되는 dependency js들 정리. 


<Babel>

ES6등으로 된 javascript를 현재 브라우저에서도 동작하게 낮은버전(ES5)등으로 변환해주는 도구

.babelrc파일만 작성하면 된다.

{
"presets": [
[ "env", { "modules": false } ]
]
}


<underscore> - lamda or function program과 유사한 함수들을 지원.  (음, lodash와 차이는?)

_.map
_.each 

_.filter

_.isEqual (A, B) : 두 Object간 동일한지 비교한다. 



<Tether> 

javascript로 webpage생성시,

포지션을 해주는 library이다.   REF


Attathment,

Offset,

pin,

to

등의 javascript tag 를 이용해 자유롭게 포지셔닝이 가능하다. 



====개발/Test용 js===========


chai : BDD, TDD assertion Library

cross-env :  bash/window등에 상관없이 환경제공. 주로 webpack.config.js안에서 사용.

del : 삭제용 js - 주로 gulpfile.js 안에서  gulp.task('clean')에 사용.


karma: karma.conf.js를 이용해서 test용  task를 생성시 사용.  

  karma-chai : 위의 chai와 결합
  karma-mocha : mocha (async한 test) 와 결합.. 주로 describe("blabla text", function() ) 형태를 많이 사용.


  karma-phantomJS:  phantomJs( Dom핸들링, CSS, JSON등 처리) 와 결합해서 브라우저 흉내를 제공.


requireJs : (AMD구현체  이해와 개발 글 참고- REF
   주로 js의 제일앞에 require()를 많이 사용했으나, function과 결합해 사용가능


runsequence : gulpfile.js안에서 default실행순서를 정의.
  



Posted by yongary
,

ES6, class let ${}....

javascript 2017. 7. 20. 18:17

ES6_turorial.pdf  

ES6 javascript 는 지원되는 브라우저가 많지 않아서 그 사용용도가 제한적이지만.. 

   1. node.js를 이용한 서버개발

  2. 관리자 페이지 (브라우저를 제한 가능)

등에서 사용이 가능하다.

Babel을 사용하면 es6파일을 es5로 변환시켜 준다.  REF


기존 javascript대비 특이한 점들은....


1. class & extends 지원  ref

    - class constructor에( options 사용가능: json 형식)
    

2. let , const 지원  
    - let은 함수도 지정이 가능한 var로서
      let add = (a,b) => a+b    ref      (lambda도 지원)   =>이다. (java는 ->임) 

    -let은 block scoping이 된다. (가능하면 let을 써야겠군요)   REF (이하 3~5))

3. Promise   (java의 Future느낌) , 그리고     tutorial.pdf에 의하면 Map,Set도 지원. 
    - .resolve()  .reject()  .all() 등 

4. import  / export  : Babel등과 함께 사용: ref

5. template  :  ${변수}       let message = `Hello ${name}!`;  

6. module 지원: REF  (webpack의 기능을 일부 담당가능)


 배열을 파라미터로 전달. 
   - 
var data = [1,2]; function Test1(a,b)...; ==> Test1(...data) : (이경우 ...을 spread라고 부른다 REF)

   -  기존 parameter들은  지정하지 않아도, arguments변수에 자동으로 넘어갔지만
       (...args) => { console.log(args); }  지원.     (이경우 ...을 REST 파라미터 라고 부른다) 

Posted by yongary
,

한글 REF성능개요    REF


  - angular과 달리, 단방향 data-binding임.


  


new Vue {     :html element를 하나 물고 있는 느낌의 객체.(물론 el없이 js ES6 class처럼 사용도 가능)

  el:  ,

   - template: ,

   

  props:  data전달 -  REF:vuejs.org  - $emit하고나서 props:로 데이타를 받음.

  data: ,

  created:  ,    //instance가 생성되고 나서 호출되는 hook.  REF'

    - mounted:
    - updated:
    - destroyed:  이런 hook들도 존재. 


  watch: 

  computed:  sort나 filter들을 적용해서 보여줄 수 있음.

   

  methods:

  validations:     ($v로 인용가능)


  components:    REF

}



- ajax요청시에는 axios 를 사용. REF

- vuelidate :  vue component의 validations: 을 check:  REF


- vue-loader : webpack에서 사용하는 loader로서, css후처리등도 가능하다고 하는데...   REF

- vee-validator 로 각종 html input등의 type/regex 체크 가능.   REF


(plugin) - plugin제작가이드 

- vue-router : 해당 component를  화면에 그려줌.     
- vuex : 전역변수                     routre/vuex REF



$router, $v (이하/위 참조),  $emit(현재 instance에 event trigger) 

========  API-list  =====================================================

:is <component :is="componentId"> <component v-bind:is="currentView">


v-for  REF

v-show

v-if

v-on:click   =>    @on(click) 으로 이벤트 감지. 
                           v-on:click="$router.push('/detail')":서브페이지로 이동.ps://router.vuejs.org

                  원복: $router.push('/')   REF:rotuter.vuejs.orghtt           

v-model   양방향 바인딩 지원.  angular.js 처럼  .sync 키워드 필요.  

v-bind

v-cloak

Posted by yongary
,

빌드자동화툴 gulp

javascript 2017. 7. 19. 18:10

REF


gulp는 js빌드자동화 툴로서, node.js를 기반으로 node의 스트림을 사용해서 동작한다.


 - gulpfile.js파일에 설정내용.

   gulp.src ([a.js, b.js...]);

   gulp.task(name, (선행잡), function)


$ gulp task-name  :시 특정 task 실행.



추가 API 한글 : REF

API Doc: REF





Posted by yongary
,

javascript의 xmlHttpRequest는 보안의 문제상, 기본적으로 현재 접속한 서버만 접속해서 이런저런 데이타를 받아올 수 있다.


하지만 복잡한 요구사항이 증가하면서, 이를 회피할 방법이 필요한 경우가 다수 생기면서

이를 회피하는 방법이 몇가지 있는데


REF

대표적인 것이 

 - CORS이다. library도 있으므로 다운받아서 쓰면 된다.  


그외  

 -JSONP (보안이 없는 js다운로드 방식을 우회해서 xml다운로드)방식도 있다.




서버사이드가 spring일 경우에   spring-doc-cors  REF 참조.


==> @CrossOrigin 어노테이션 및   

      Config에서  allowedOrigin하는 방법이 대표적.

@Bean

    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/greeting-javaconfig").allowedOrigins("http://localhost:9000");
            }
        };
    }


Posted by yongary
,

화면의 table 에 이미 있는 내용을 사용자가 또 추가입력하는 경우

(즉, 팝업을 통해서 새로운 데이타를 추가하는데,  화면에 이미 있는내용과 중복되는지 체크하는 경우)


서버를 통하지 않고, jQuery를 통해서 쉽게 방지해서 alert창을 뛰울 수 있다.






<script type="text/javascript"> function nameCheck() { var name = $('#myInput').val();

if ($('.listedName:contains(' + name + ')').length != 0) {
alert('already Exists');
return false;
}
return true;
} </script>



<table>
<tr>
<td>ID1</td>
<td class="listedName">name1</td> // name2, name3 등 반복

</tr>


.....

<form onsubmit="'return nameCheck()'">

<input id="myInput"/>


그런데, contains함수가 문제가 약간있다.

Entity단위(테이블 TD단위)로 비교를 하지 않고...    Entity안에 단어가 포함되는지를 비교하는 문제가 있다.


그래서  정확하게 비교를 하고 싶을때는 filter를 쓸 필요가 있다.  REF


if ($('.listedName').filter(function() {
return $(this).text() === name;
}).length !=0 ) {


Posted by yongary
,

javascript로 이메일 verification하는 스크립트가 왜케 복잡한 것만 있는지..


인터넷에 마음에 드는 게 없어서 새로 만들어 보았다.



//check if mail address is xx@xx.xx (xx: contains "." & "_" & "-" & "alphanumeric" )
function validateEmail(email) {
var re = new RegExp("^[-a-zA-Z0-9._]+@[-a-zA-Z0-9._]+\\.[-a-zA-Z0-9._]+$");
return re.test(email);


코멘트 처럼  xx@xx.xx  폼을 체크하는데  xx 는  - . _ 알파뉴메릭  으로 이루어진다. 



조금 더 발전하면.. (이건 다른사람 꺼)

"[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})";


Posted by yongary
,

ExtJS, Sencha

javascript 2015. 12. 26. 15:23

ExtJS:  개인적으로 느낀 느낌은 .. 조직도 가 잘 구현되어 있는 JS이다.

 

 

예제:  http://dev.sencha.com/deploy/ext-4.0.0/examples/#sample-3

 

기본: http://rhio.tistory.com/240

        http://rhio.tistory.com/350 

 

 

 

Sencha Touch: REF-SITE

Sencha Touch는 Mobile Web Application 개발을 위한 JavaScript Framework 입니다. Mobile에 최적화된 기능을 탑재하고있으며 폰과 태블릿 기기를 위한 Framework 입니다. Sencha Touch는 ExtJS 개발사의 Framework이며 JavaScript, CSS, HTML 등 순수 웹 기술만으로 네이티브 스타일을 표현할 수 있도록 함.

Posted by yongary
,

javascript관련 질문들:

 

javascript에는 function statement와 function expression이 존재한다.

비슷하지만 약간의 차이가 난다.

 

<Function>

  - function expression: var x = function fname(){}   (fname is optional) 

 => 이걸로 싱글턴 만들수 있다. class만들고 싱클턴 만드는 거 보다 less expensive.

  - function statement:   function fname(){}

 

<기타>

  - javascript 에 {blocks}  는  scope을 가지지 않는다. 

 

<슈도 파라미터 2가지>

  - arguments : parameter와 밀접한 관계가 있으므로, read-only로 사용하는 게 좋다.

       일종의 array로 최근(ES5)에 .reduce 등이 소개되었다. 
         arguments.length

         arguments[i]

 

  - this : function 내에서 멤버변수를위한 public 키워드처럼 동작하기도 하며, (이건 아래2번)

1. reference to the object of invocation

2. allows to know the concerned Object

3. allows single function object to service many functions ?

4. key to prototype inheritance

 

Function.prototype.bind를 통해 this를 강제로 할당 할 수 있다.

 


<prototype이란>

All JavaScript objects inherit the properties and methods from their prototype.

Allows you to add properties and methods to an object 

we can inherit using prototype. and by overriding construct(). => prototype is copied.




<function관련 Form종류들>

  - New폼:      new functionObject() 

  - function폼: functionObject(arg) 이 경우, var that = this; 많이 사용. inner function이 outer를 접근하기 위해서..
                     (왜냐면 자체 this가 있기 때문)

  - method폼:  functionObject(arg).method()

  - apply폼:    apply()  form  ,   유사한것으로 call도 있는데, apply는 (this,array)  call은 (this, a,b,c : each object of array)가 전달된다.

 

 

this 참고사이트:  http://mobicon.tistory.com/189  

유투브:   15분-this,  30분-closure  (English)








Posted by yongary
,

hoisting, strict mode

javascript 2015. 8. 4. 19:19

javascript에서 hoisting이란 

 변수나 함수를 var 로 선언하기 전에도 사용할 수 있다는 의미이다.  참고사이트

(global함수의 경우는 어디서나 사용할 수 있으므로 hoisting이 아니다.)


참고사이트:영어

In JavaScript,  a variable can be used before it has been declared.


hoisting이 왜 중요한가?

==> 크드가 잘 돌아가더라도 hoisting이 동작한 것일 수 있기 때문에, hoisting을 알아두는 것이 각종버그를 방지할 수 있다.


strict mode : "use strict";  를 사용하면  hoisting을 방지할 수 있다. (꼭 선언 후 사용하는 모드)  w3schools_js



Posted by yongary
,

(팁: 크롬으로 javascript 개발시 F12 키가 debug모드이다 :   메뉴엔 Ctrl-Shft-J)



JavaScript의 객체 상속도를 잘 나타낸 그림은 다음과 같다.  참고사이트:devbox


DOM구조에서 거의 모든 object들이 Node를 상속받아서 만들어 졌다고 보면된다.

그런데 개발시에는 node API를 쓰면 필요없는 tag등이 한번씩 나오는 경우가 있어서

위한 children() 함수를 더 많이 쓰게 된다. 


<많이 쓰는 코드>

    document.getElementById('aa').children  -> HTMLCollections 를 리턴함.

    

    (document.getElementByxxx부터 해서,  Element를 특히 많이 씀)

    document.getElementById('aa').children.item(i)  --> Element 리턴.

jquery의 경우는 : $('#aa')[0].childNodes[0].nodeValue;

  $($('h1').contents().get(0)).text(); //.get(0)=[0]

  $('h1').contents().each(function() {
          
if(this.nodeType == 3) { }


    removeChild(e) 

    appendChild(e)

    document.createElement('div')





Posted by yongary
,

참고사이트: Javascript 재입문


parseInt( "11", 2) = 3

NaN : Not a number    

Infinity : 무한대   1/0 = Infinity


1==true : true   (type이 오토케스팅 됨)

1===true: false  (===: type 강제변환 방지: type까지 비교함. )

 

var names;   //names == undefined임.

  이 때, !names == !undefined  //둘다 true임. 

 

setTimeout(func, 100) //0.1초 후 실행.

setInterval(func,100)  //0.1초씩 반복


for (var i in a)  //a[i]사용가능,   var a=["dog","cat","chicken"]

 

<주의>

var z = 0.1 + 0.2;  //z=0.300....4   모든 수가 64bit float이라 계산에 오류발생 가능.

javascript는 head나 body에 모두 사용가능하다.

==의 반대말은 !=  ( <>아님)

javascript는 당근 case Sensitive하다.

 

 

<JS object>

var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};  ==> prototype기반 function보단 사용용도가 약하지만, JSON은 큰 장점.

 

<array>

[1,2].concat([2,3]);  //Array.concat => [1,2,2,3]  혹은 arrA.concat(arrA)

[2,3,4].join()   // toString.. "2,3,4"

 

 

<기타>

navigator.userAgent;

navigator.appName ;  브라우저 name

window.btoa("abc") //=> base64 encoding.

 

<< My experience >>

new window['Pattern'+ i]()           //= new Pattern1 ~ new Pattern6

apply(obj, [a,b])  or   call(obj, a,b)   // 0bj->this, (a,b)   this chapter 참조.  

Posted by yongary
,

SPA를 위한 여러가지 framework들이 있지만, framework없이 간단한 library로만

js SPA를 구현하는 방법이 있다.

 

http://tutorialzine.com/2015/02/single-page-app-without-a-framework/ 

 

 

 handlebars.js 를 사용한다.

 

Posted by yongary
,

key

javascript 2015. 4. 2. 23:07

<key event>

document.onkeydown=checkKey;

function checkKey(e){

  if(e.keyCode=='37'){  //left Key, 38:up, 39:right, 40:down

     alert('left');

  }

}



Posted by yongary
,

closure

javascript 2015. 4. 2. 09:39

클로져에 대해서 나름대로 정리해보면,

아래와 같은 함수에서 MyClass을 outter함수라고 부를때,

내부 함수 (gettitle)가  outter의 지역변수를 계속 사용할 수 있다는 개념.  

(javascript의 initialize비용이 비싸므로, closure를 이용해서 inner함수 안에서 if(!undefined) define을 할 수 있다.)

 ==> Point: 외부함수가 종료된 이후에도 사용할 수 있다.


var that=this 로 해서, this도 많이 사용한다고 한다. 이렇게 안하면 this가 전역변수인 window를 나타낼 수 있기 때문...



function MyClass(_title){

  var title=_title;

  return{   //json스타일 객체를 return.

     getTitle:function() { return title;},

  }

}


g=MyClass('ggg');

m=MyClass('mmm');


alert(g.geTtitle());   //m.getTilte()도 잘 동작.




참조: devbox

      Nonblock

Posted by yongary
,

eclipse js 환경

javascript 2015. 4. 1. 08:31

1. Web, OSGI  를 설치한다. (for Web,  install new software 에서)

  참고사이트: http://fishbear.tistory.com/2


2. JSDT 를 설치. (for JS,  eclipse marketplace 에서)

   - jsdt for jQuery 

   - angularJS eclipse(0.10.0?)

   - jsdt for ExtJS (1.7?)



속성 js Lib에서 jQuery등 추가하고..( ECMA, jQuery, ExtJS..)

$('head').   (점찍고 Ctrl+Enter로 확인)

Posted by yongary
,

HTML5

javascript 2015. 3. 31. 14:55

HTML5는 javascript의 확장판이라고 볼 수 있다.


이 중에서 쓸만한 것들을 나열해보면


1.Geolocation


2.Web Storage


3.IndexedDB + Object Store


4.Application Cache


5.WebSocket


6.File API


7.Drag & Drop 





그 외 5개+1는 천천히 알아보자

Server-Sent Event

Web Workers

WebGL

Selector API

Notifications API

Web SQL DataBase(2009년 중단된듯 )





Posted by yongary
,

javascript 상속

javascript 2015. 2. 4. 21:46

javascript에서의 상속은 일반적인 OO와 다르다.

그 이유는 javascript가 OO 언어가 아니고, 함수(prototype)기반 언어라서 그러하다.


대신, prototype과  prototype.constructor를 치환하는 방법으로 상속이 구현 가능하다.



<<예제>>

    function AjaxBasic(){

        if ( window.XMLHttpRequest){

            this.xhr = new XMLHttpRequest();

        }else{

            console.log("NO XHR support maybe ~ IE6");

            return;

        }

        this.xhr.onreadystatechange=function(){

            if (ajaxObj.xhr.readyState==4 && ajaxObj.xhr.status==200)

                document.body.innerHTML=ajaxObj.xhr.responseText;

        }

        //// method..  run()

        this.run = function(){ 

            this.xhr.open("GET", "test_data.txt", true);

            this.xhr.send();

        }

    }


    function MyAjax(){

        this.run = function(fileUrl){

            ajaxObj.xhr.open("GET", fileUrl, true);

            ajaxObj.xhr.send();

        }

    }



   ///Inherit =  prototype + constructor

    MyAjax.prototype = new AjaxBasic();

    MyAjax.prototype.constructor = MyAjax();


Posted by yongary
,

ajax

javascript 2015. 2. 4. 21:31

간단한 ajax .


function makeRequest(url)
{
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);  //true is A of Ajax=Async
    xhr.onreadystatechange = receiveResponse;
    xhr.send();
}
function receiveResponse(e)
{
    if (this.readyState == 4) //4:complete
    {
        if (this.status == 200) //200 ok
        {
            var response = this.responseXML;
            ...
        }
    }
}


웹페이지 버튼 콜백 ajax ( JQuery 경우)  - 아래에서 CDATA는 없어도 됨. 

<script type="text/javascript" th:inline="javascript">
/*<![CDATA[*/
$(function () {
$('.clear-cache').click(function () {
$.ajax({
type: "POST",
url: "/api/internal/v1/clear_cache/banner",
success: function () {
$('#clearCacheModal').modal('show');
}
});
});
});
/*]]>*/
</script>


Posted by yongary
,