반응형

자바 스크립트는 서로 다른 도메인에 대한 요청을 보안상 제한합니다. 이 정책을 동일근원정책(Same-Origin Policy, SOP) 정책이라고 하며, 이러한 정책으로 인해 생기는 이슈를 cross-domain 문제라고 합니다. 
개발을 하다보면 어쩔 수 없이 다른 도메인으로부터 데이터를 가져와야 하는 경우가 많기에 많은 사람들이 cross-domain 이슈를 겪고 있습니다.

이런 경우 사용할 수 있는 것이 JSONP(JSON with Padding)입니다. 처음 JSONP를 접했을 때 잘 정리가 되지 않았던, 사용할 때 명확히 알아야 할 것들을 정리해보았습니다.

 

1. JSONP 요청은 일반 AJAX 요청과 다르다

//-- JSON
$.ajax({ 
    url: url, 
    dataType: 'json', 
    data: data, 
    success: callback 
}); 
$.getJSON(url, data, callback);

//-- JSONP
$.ajax({ 
    url: url, 
    dataType: 'jsonp', 
    jsonpCallback: "myCallback", 
    success: callback 
}); 
$.getJSON(url + "?callback=?", data, callback);

dataType 만 변경하거나, 요청 url 뒤에 callback 파라미터 를 붙일 뿐입니다. 그렇지만 이것만으로도 완전히 다른 동작 을 하게 됩니다.

 

2. ‘JSONP’라는 데이터 타입 요청이 아닌 <script> 호출 방식

JSONP는 HTML의 script 요소로부터 요청되는 호출에는 보안상 정책이 적용되지 않는다는 점을 이용한 우회 방법 입니다.

다시 한번 확실히 하자면, script 요소는 src를 호출한 결과를 javascript를 불러와서 포함시키는 것이 아니고 실행시키는 태그입니다.

 


3. JSONP Callback은 서버에서 지원해줘야 한다
알아두어야 할 중요한 것은 응답 데이터는 Text형 이란 것과, callback 함수명으로 감싸진다 는 점 입니다.
 

"myCallback({'name':'test','age':28})"
 
 
 
 
 $.ajax({ url: url, dataType: 'jsonp', jsonpCallback: "myCallback", success: callback });
 
 $.getJSON(url + "?callback=?", data, callback);

위 요청을 해석해보자면,

  • cross-domain 이슈를 회피하기 위하여 jsonp 요청을 한다
  • 응답 데이터는 myCallback(결과) 형태의 text로 wrapping 되어질 것이다.
  • myCallback이란 함수를 나의 success function에 mapping 시킬 것이다.

가 됩니다.

 

github.com/kingbbode/spring-jsonp-server
 

 

kingbbode/spring-jsonp-server

Jsonp Server Example. Contribute to kingbbode/spring-jsonp-server development by creating an account on GitHub.

github.com

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Kingbbode</title>
    <script
    src="https://code.jquery.com/jquery-2.2.4.min.js"
    integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
    crossorigin="anonymous"></script>
  </head>
  <body>
    <script>
    var url = 'http://localhost:9000/';
    var static_json = 'http://localhost:9000/json/test.json'
    $.ajax({
      url: static_json,
      dataType: 'jsonp',
      jsonpCallback: "myCallback",
      success: function(data){
        console.log('ajax', data);
      }
    });

    $.getJSON(url + "?callback=?", function(data){
      console.log('getJSON', data);
    });
    </script>
  </body>
</html>
반응형
반응형

Ajaxload gif

www.ajaxload.info/

 

Ajaxload - Ajax loading gif generator

Ajaxload (Beta) <- Hey ! This service is Web 2.0 Preview Create easily your own ajax loader icon : Select the type of indicator you want Enter the background code color you want (tick "Transparent background" if you don't want one Enter the foreground code

www.ajaxload.info

반응형
반응형

Internet Explorer 에서의 ajax 에서의 한글 깨짐 현상

IE에서만 encodeURI를 적용하는게 맞다.

// 윈도우인지 다른 브라우저인지 확인 
            var ua = window.navigator.userAgent;
            var postData;
            // 윈도우라면 ? 
            if (ua.indexOf('MSIE') > 0 || ua.indexOf('Trident') > 0) {
                postData = encodeURI(sendData);
            } else {
                postData = sendData;
            }

            $.ajax({
                url: "thumnailUpload.php", // Url to which the request is send
                type: "POST",             // Type of request to be send, called as method
                data: postData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                contentType: false,       // The content type used when sending data to the server.
                cache: false,     

 

반응형

'프로그래밍 > Script' 카테고리의 다른 글

JSFIDDLE - https://jsfiddle.net/  (0) 2020.01.10
12 Extremely Useful Hacks for JavaScript  (0) 2019.12.31
JSON Editor Online  (0) 2019.11.26
[jQuery] AJAX Cross Origin plugin  (0) 2019.10.21
javascript, nl2br, nl to &nbsp;  (0) 2019.09.11
반응형

 AJAX Cross Origin plugin


로컬 프록시를 작성할 필요없이 Cross Origin AJAX 요청을 허용하는 jQuery 플러그인입니다.   

http://www.ajax-cross-origin.com/

 

Ajax Cross Origin - jQuery plugin

Source code In order maintain this site and keep it running, we ask for symbolic donation before you download the sources. You can donate as much as you want, even $1 is enough. The package contains the source code files include instructions and a test pag

www.ajax-cross-origin.com

<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script type="text/javascript" src="js/jquery.ajax-cross-origin.min.js"></script>
</head>

<body>

<select id="service">
  <option value="http://ip.jsontest.com/">IP Address</option>
  <option value="http://headers.jsontest.com/">HTTP Headers</option>
  <option value="http://date.jsontest.com/">Date & Time</option>
  <option value="http://echo.jsontest.com/key/value/one/two">Echo JSON</option>
  <option value='http://validate.jsontest.com/?json={"key":"value"};'>Validate</option>
  <option value="http://code.jsontest.com/">Arbitrary JS Code</option>
  <option value="http://cookie.jsontest.com/">Cookie</option>
  <option value="http://md5.jsontest.com/?text=[text%20to%20MD5]">MD5</option>
</select><br/>
<input type="text" id="url" style="width: 400px">
<input type="button" id="btn" value="Get JSON">
<br/><br/>
<div id="test" />

<script type="text/javascript">
$(function() {
  $( '#service' ).on( 'change', function(){
    $( '#url' ).val( $( this ).val() );
  });
  
  $( '#url' ).val( $( '#service' ).val() );
  
  $( '#btn' ).click(function(){
    var url = $( '#url' ).val()
    
    $.ajax({
      crossOrigin: true,
      url: url,
      success: function(data) {
        $( '#test' ).html(data);
      }
    });
  });
}); 
</script>

</body>
</html>
반응형
반응형

Apy: A library for rest API ajax calls

Apy is a client-side library for making rest API ajax calls. It’s simple, well-documented, and easy to get started with.

apy

반응형
반응형

Monsta FTP — FTP cloudware

monsta ftp

 

반응형
반응형


ajax() 메소드는 비동기 요청을 수행.

 

http://api.jquery.com/jQuery.ajax/
http://www.w3schools.com/jquery/ajax_ajax.asp

 

jQuery.ajax( url [, settings ] )Returns: jqXHR

  $.ajax({
     url:"demo_test.txt",
     success:function(result){
       $("#div1").html(result);
   }});


getJSON() 메소드는 AJAX HTTP Get 요청을 사용하여 JSON 데이터를 가져온다.

 

http://api.jquery.com/jQuery.getJSON/
http://www.w3schools.com/jquery/ajax_getjson.asp

 

jQuery.getJSON( url [, data ] [, success(data, textStatus, jqXHR) ] )Returns: jqXHR

 

$.getJSON('http://yoururl?callback=?', function(data){alert(data)});

 

var jqxhr = $.getJSON( "example.json", function() {console.log( "success" );})
             .done(function() { console.log( "second success" ); })
             .fail(function() { console.log( "error" ); })
             .always(function() { console.log( "complete" );
             });
             // perform other work here ...
             // Set another completion function for the request abovejqxhr.complete(function() { console.log( "second complete" ); });

 

jqxhr.complete(function() { console.log( "second complete" ); });

 

 

getScript() 메소드는  AJAX HTTP GET 요청을 이용하여 javascript를 실행한다.

 

http://api.jquery.com/jQuery.getScript/

 

jQuery.getScript( url [, success(script, textStatus, jqXHR) ] )Returns: jqXHR

 

$.getScript("demo_ajax_script.js");

 

$.getScript("ajax/test.js", function(data, textStatus, jqxhr) {  
                     console.log(data); //data returned  
                     console.log(textStatus); //success  
                     console.log(jqxhr.status); //200  
                     console.log('Load was performed.');});

 

$.getScript("ajax/test.js").done(function(script, textStatus) { 
                                    console.log( textStatus );})
                           .fail(function(jqxhr, settings, exception) { 
                                    $( "div.log" ).text( "Triggered ajaxError handler." );
                           });

 

 

 

 

반응형
반응형

iOS6 SAFARI BUG (iOS6 사파리 버그 - AJAX, SPINNING, ...)

아이폰5 발표가 되고 조금 지나서 iOS6도 공개가 되었다.


업데이트평은

인터넷 접근 속도가 빨라졌다.

OS 전체적으로 조금 빨라졌다 라는 평이 많고..

일부 아이폰 4이하 기기를 사용하시는 분들은 느려졌다는 의견도 좀 있다.



뭐.. 그런저런 이야기는 지나가고..


개발을 하고 사용하다 보니 문제가 발생했다.

바로바로...

AJAX caching bug


사이트에서 페이지가 바뀌지 않은 상태에서

AJAX를 재호출 했을 경우 이전에 받았던 데이터를 그냥 계속 불러오는 버그가 발생하였다.


예상되는 버그 시나리오



* 최초로 A data("test.jsp")를 요청

   1. 서버로 A data를 요청

   2. 서버에서 Safari로 전달

   3. Safari에서는 해당 데이터를 캐쉬에 저장

   4. A data 제공


* 이후에 A data("test.jsp")를 요청

   1.  Safari Cache에 해당 데이터가 있는지 확인

   2.  Cache에 있는 A data 제공



해당 문제가 발생하는 이유

브라우저가 인터넷 속도를 빠르게 하기 위해서 캐시를 사용을 하게 된다.

이럴 경우 같은 주소에 대해서는 캐시를 사용하면서 생기는 문제로 보인다.



해결책


1. 주소에 쓰레기 값을 붙여서 새로운 주소로 인식하도록 한다.

ex) test.jsp?timeStamp=93939393


2. meta cache control을 추가해준다.

ex) <meta http-equiv="Cache-Control" content="no-cache" />


3. 서버 HEADER를 추가해준다.

ex) header('cache-control: no-cache');



1, 2번을 함께 적용하여 해결을 했다.


관련 URL를 참고하면 자세한 정보가 나와있으니 참고하도록.





아......... 애플.. ㅡ.ㅡ;;


ps.

iOS6 Webview에서도 동일한 증상이 발견된다.

즉............. 어플도 확인해봐야한다는 말씀?!



관련 URL

Understanding the iOS6 AJAX bugs

http://www.devthought.com/2012/09/22/understanding-the-ios6-ajax-bugs/

1. The spinning bug

2. The AJAX cache bug

3. The long-polling bug


Is Safari on iOS 6 caching $.ajax results?

http://stackoverflow.com/questions/12506897/is-safari-on-ios-6-caching-ajax-results


AJAX Web Apps In iOS 6 Are Sort Of Broken

http://techcrunch.com/2012/09/21/ajax-web-apps-in-ios-6-are-sort-of-broken/



반응형

+ Recent posts