728x90

Query.getScript()

원문 링크  http://api.jquery.com/jQuery.getScript/

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

개요 : HTTP GET 방식 요청을 통해 서버로부터 받은 JavaScript 파일을 로드하고 실행합니다.

  • jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )
  • url 정보를 요청할 URL
  • success(data, textStatus, jqXHR) 요청이 성공하면 실행될 콜백 함수

이 함수의 가장 간단한 사용법은 아래와 같습니다.

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

스크립트가 실행되면 다른 변수에서 접근이 가능하고 jQuery 함수에서도 사용할 수 있습니다. 포함된 스크립트는 현재 페이지에 영향을 줄 수 있습니다.

Success Callback

이 콜백함수는 JavaScript 파일을 반환 받습니다. 스크립트가 이미 이 시점에서 실행되므로 이것은 일반적으로 유용하지 않습니다.

$(".result").html("<p>Lorem ipsum dolor sit amet.</p>");

스크립트는 파일이름을 참고한 후 로드하고 실행됩니다.

$.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.');
});

Handling Errors

jQuery 1.5 부터 .fail() 함수를 사용할 수 있게 되었습니다.

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

jQuery 1.5 이전 버젼에서는, .ajaxError() 콜백 이벤트에 $.getScript() 에러 처리 구문을 포함해서 사용해야 합니다.

$( "div.log" ).ajaxError(function(e, jqxhr, settings, exception) {
  if (settings.dataType=='script') {
    $(this).text( "Triggered ajaxError handler." );
  }
});

Caching Responses

기본적으로 $.getScript() 의 cache 속성값은 false 입니다. 스크립트를 요청시에 URL에 timestamped 를 포함하여 브라우져가 항상 새로운 스크립트를 요청하도록 하십시오. cache 속성의 전역값을 새로 세팅하려면 $.ajaxSetup()에서 하셔야 합니다.

$.ajaxSetup({
  cache: true
});

예 제  
캐싱된 스크립트를 가져올 수 있도록 $.cachedScript() 함수에서 정의합니다.

jQuery.cachedScript = function(url, options) {

  // allow user to set any option except for dataType, cache, and url
  options = $.extend(options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });

  // Use $.ajax() since it is more flexible than $.getScript
  // Return the jqXHR object so we can chain callbacks
  return jQuery.ajax(options);
};

// Usage
$.cachedScript("ajax/test.js").done(function(script, textStatus) {
  console.log( textStatus );
});

음, 솔직히 말씀드려서 위 예제가 실행되면 어떻게 된다는 건지 정확하게 모르겠습니다. :-(

 

예 제  
공식 jQuery 컬러 애니메이션 플러그인 파일을 로드하고 특정 컬러를 반영합니다.

<!DOCTYPE html>
<html>
<head>
  <style>
.block {
   background-color: blue;
   width: 150px;
   height: 70px;
   margin: 10px;
}</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<button id="go">&raquo; Run</button>

<div class="block"></div>

<script>
$.getScript("/scripts/jquery.color.js", function() {
  $("#go").click(function(){
    $(".block").animate( { backgroundColor: "pink" }, 1000)
      .delay(500)
      .animate( { backgroundColor: "blue" }, 1000);
  });
});
</script>

</body>
</html>

미리보기

jquery.color.js 파일을 열어보세요. 무지 복잡하게 뭐라무라 되어 있네요. 그중에 colors = jQuery.Color.names 변수에 위 예제에 있는 blue와 pink 에 대한 16진수 값이 들어 있습니다. 그 js 파일을 열어서 관련 로직을 반영시키는 것입니다.

 

음;;; 이 방식이 딱히 필요한지 모르겠습니다만.... 어디선가 쓸일이 있을지도 모르겠네요. 사용해 보신 분들 사례 좀 말씀해 주세용!!

※ 본 예제는 http://www.jquery.com 에 있는 내용임을 밝힙니다.



출처: http://findfun.tistory.com/397 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/397 [즐거움을 찾자 Find Fun!!]

출처: http://findfun.tistory.com/397 [즐거움을 찾자 Find Fun!!]

'WEB > jQuery' 카테고리의 다른 글

특정 div 프린트 하기  (0) 2018.05.11
Returning JSON data using jQuery POST function from server  (0) 2018.05.10
Refresh Part of Page (div)  (0) 2018.04.13
jQuery Select Box Control  (0) 2018.04.13
turn.js  (0) 2018.03.08
728x90


I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.

Use Ajax for this.

Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.

Relevant function:

http://api.jquery.com/load/

e.g.

$('#thisdiv').load(document.URL +  ' #thisdiv');

Note, load automatically replaces content. Be sure to include a space before the id selector.


    728x90

    JQuery에 다른 기능을 검색하다가 아래의 사이트를 발견하여 나중에 도움이 될 듯하여 정리해둔다.


    1. jQuery로 선택된 값 읽기

     

    $("#selectBox option:selected").val();

    $("select[name=name]").val();

     

    2. jQuery로 선택된 내용 읽기

     

    $("#selectBox option:selected").text();

     

    3. 선택된 위치

     

    var index = $("#test option").index($("#test option:selected"));

     

    4. Add options to the end of a select

     

    $("#selectBox").append("<option value='1'>Apples</option>");

    $("#selectBox").append("<option value='2'>After Apples</option>");

     

    5. Add options to the start of a select

     

    $("#selectBox").prepend("<option value='0'>Before Apples</option>");

     

    6. Replace all the options with new options

     

    $("#selectBox").html("<option value='1'>Some oranges</option><option value='2'>MoreOranges</option>");

     

    7. Replace items at a certain index

     

    $("#selectBox option:eq(1)").replaceWith("<option value='2'>Someapples</option>");

    $("#selectBox option:eq(2)").replaceWith("<option value='3'>Somebananas</option>");

     

    8. 지정된 index값으로 select 하기

     

    $("#selectBox option:eq(2)").attr("selected", "selected");

     

    9. text 값으로 select 하기

     

    $("#selectBox").val("Someoranges").attr("selected", "selected");

     

    10. value값으로 select 하기

     

    $("#selectBox").val("2");

     

    11. 지정된 인덱스값의 item 삭제

     

    $("#selectBox option:eq(0)").remove();

     

    12. 첫번째 item 삭제

     

    $("#selectBox option:first").remove();

     

    13. 마지막 item 삭제

     

    $("#selectBox option:last").remove();

     

    14. 선택된 옵션의 text 구하기

     

    alert(!$("#selectBox option:selected").text());

     

    15. 선택된 옵션의 value 구하기

     

    alert(!$("#selectBox option:selected").val());

     

    16. 선택된 옵션 index 구하기

     

    alert(!$("#selectBox option").index($("#selectBox option:selected")));

     

    17. SelecBox 아이템 갯수 구하기

     

    alert(!$("#selectBox option").size());

     

    18. 선택된 옵션 앞의 아이템 갯수

     

    alert(!$("#selectBox option:selected").prevAl!l().size());

     

    19. 선택된 옵션 후의 아이템 갯수

     

    alert(!$("#selectBox option:selected").nextAll().size());

     

    20. Insert an item in after a particular position

     

    $("#selectBox option:eq(0)").after("<option value='4'>Somepears</option>");

     

    21. Insert an item in before a particular position

     

    $("#selectBox option:eq(3)").before("<option value='5'>Someapricots</option>");

     

    22. Getting values when item is selected

     

    $("#selectBox").change(function(){

               alert(!$(this).val());

               alert(!$(this).children("option:selected").text());

    });


    출처 : http://blog.daum.net/twinsnow/124

    728x90


    Make a flip book with HTML5

    • Works on most browsers and devices
    • Simple and clean API
    • Lightweight, 10K

    Download

    ↑ Click a book or magazine to see turn.js in action

    Turn.js is a JavaScript library that will make your content look like a real book or magazine using all the advantages of HTML5. The web is getting beautiful with new user interfaces based in HTML5; turn.js is the best fit for a magazine, book or catalog based in HTML5.

    Let's code

    <div id="flipbook">
    	<div class="hard"> Turn.js </div>
    	<div class="hard"></div>
    	<div> Page 1 </div>
    	<div> Page 2 </div>
    	<div> Page 3 </div>
    	<div> Page 4 </div>
    	<div class="hard"></div>
    	<div class="hard"></div>
    </div>
    
    <script type="text/javascript">
    	$("#flipbook").turn({
    		width: 400,
    		height: 300,
    		autoCenter: true
    	});
    </script>
    

    Features

    • ✓   Works on iPad and iPhone.
    • ✓   Simple, beautiful and powerful API.
    • ✓   Allows to load pages dynamically through Ajax requests.
    • ✓   Pure HTML5/CSS3 content.
    • ✓   Two transition effects.
    • ✓   Works in old browsers such as IE 8 with turn.html4.js

    Requirements

    jQuery 1.3 or above.

    Browser Support

    Safari 5Chrome 16Firefox 10IE 10, 9, 8

    Devices

    • ✓   All iOS (iPad, iPhone, iPod)
    • ✓   Android (Chrome for Android)

    Improvements

    Turn.js 4 includes a set of significant performance improvements on its core.

    • ✓   Effects are now quite smoother on the browser platform.
    • ✓   The new DOM composition guarantees the same performance no matter the amount of pages.

    Complements

    turn.html4.js - The HTML4 version of turn.js.

    zoom.js - The new zoom feature of turn.js, See a sample.

    scissors.js - Cuts a page in two parts for turn.js.

    hash.js - Controls the navigation history using pushState and URI hashes.

    API Documentation

    The turn.js API was conveniently built as an UI plugin for jQuery, it provides access to a set of features and allows you to define the user interaction. 
    The complete documentation is available here, it's also available in PDF format.

    Support

    You can browse all issues on GitHub
    If you'd rather report issues using your email, you could contact us to: support@turnjs.com

    Licensing

    The turn.js project is released under the BSD license and it's available on GitHub. This license doesn't include features of the 4th release.

    About

    Hello Everyone, 

    I'm Emmanuel García, a front-end developer from Venezuela, who loves to push the web forward with new technologies.

    I look forward to releasing new projects. One of those will allow you to split HTML content into pages depending on the size of the pages. While loading pages with turn.js, this library would have an infinity potential. Think about detecting the number of pages automatically, creating a table of contents that knows where every page is, and adding functions like font size.

    I'm also interested in using pdf.js and node.js for a new library that will convert pdf files into pure HTML5 (text/CSS3) files to provide content for the frontend with turn.js.

    Follow me on Twitter: @blasten or Github 
    Reach me out: blasten@gmail.com

    ©2012 All rights reserved - A production of @blasten


    + Recent posts