Jquery,Coffeescript Snippet 모음


스타일 변화 시키기


    $('HTML').addClass('JS');
    * In your css */
    .JS #myDiv{display:none;}

coffee script 에서 함수 호출


    contents+="<li class='city_candidate' onclick='h(\""+data[v]+"\")'>"+v+"</li>"
    @h = h = (set) ->
      $('span#cityoutput').replaceWith("<span id='cityoutput'>"+set+"</span>")

Ajax Callback


    url = "locations"
    request = $.get url,data
    request.success (data) -> $("#regionresults").html(data)
    request.error (jqXHR, textStatus, errorThrown) -> $("#region
results").append "AJAX Error: ${textStatus}."

Slide UP


jQuery ->
  $(".search input").focus ->
    if @value == "Search"
      @value = ""
      @className = "textinput"  $(".search input").blur ->
    if @value == ""
      @value = "Search"
      @className = "placeholder"
  $('#message').css { border: '1px solid red' }
  $("p").click(function () {
      $(this).slideUp();
    });
    $("p").hover(function () {
      $(this).addClass("hilite");
    }, function () {
      $(this).removeClass("hilite");
    });

Sticky layer


sticky = () ->
  y = $(window).scrollTop()
  if y > $('#topnavigation').height()
    $('#top
navigation').css({
      'position': 'fixed',
      'top': '0',
      'z-index': "4444"
        'width': $('#top_navigation').width(), 'box-shadow': '0px 20px 20px -15px #CCC'
    })
    $('#topnavigation').removeClass("sixteen columns alpha")
    $('#main').css({'padding-top': $('#top
navigation').height()})
  else
    $('#topnavigation').removeAttr('style')
    $('#main').removeAttr('style')
    $('#top
navigation').addClass("sixteen columns alpha")
$(window).scroll(sticky)
$(window).resize(sticky)
   
   

페이드인 메시지


msg = "world"
inv = "you"
show_message = (x,y) ->
  $('span#message').hide().text(x).fadeIn(1000,
  -> $('span#message').append('!')
  )
  $('#hint').hide().text(x).fadeIn(0)$ ->
  showmessage msg,inv
    [inv, msg] = [msg, inv]
 
  $('span#message').click ->
    show
message inv,msg
    [inv, msg] = [msg, inv]
message fadein and out
.fadeIn(30).fadeOut(1000);
   

다이나믹 add remove


$('input#addlanguageskill').on 'click', () ->
  num = ($('.languageskillinnerbox').length)-1
  newNum  = new Number(num+1)
  sourceElem = $('div#language
skill' +num)
  newElem = sourceElem.clone().prop('id','language
skill'+newNum)
  newElem.find("#user
languageskillsattributes"+num+"languageid").prop({id:'userlanguageskillsattributes'+newNum+'languageid',name:'user[languageskillsattributes]['+newNum+'][languageid]'})
  newElem.append('<input onclick="remove(\''+newElem.prop('id')+'\')" id="removelanguageskill"'+newNum+' type="button" value="Remove Language"/>')
  sourceElem.after(newElem)
@remove = remove = (elemid) ->
  alert "remove : "+elem
id
  $("#"+elem_id).remove()

Nested Model Form 예제


<% formfor @person do |personform| %>  <%= personform.label :name %>
  <%= person
form.text_field :name %>
  <% personform.fieldsfor :children do |child_form| %>
    <%= childform.label :name %>
    <%= child
form.text_field :name %>
    <% unless childform.object.newrecord? %>
      <% # Don't forget to name both of these 'destroy' in Rails 3 %>
      <%= child
form.checkbox 'delete' %>
      <%= childform.label 'delete', 'Remove' %>
    <% end %>
  <% end %>
  <%= submit_tag %>
<% end %>

그리즈 몽키 ajax 콜


var jqxhr = $.ajax({
  type: "POST",
  url: trackback,
  headers: {'User-Agent': 'Trackback',
                  'Content-Type':'application/x-www-form-urlencoded; charset=utf8'},
  data: inputdata,
  datatype:"text"
   });
  jqxhr.done(function() {
    GM
log("Trackback Success : "+jqxhr.responseText);           
  });
  jqxhr.fail(function(data,statusText,error) {                
        GM_log("Trackback faild : "+statusText+" [ "+error+", "+data.responseText+" ]");              
       
       
  });
 

셀렉트 박스 정렬


sortingSelectBox(selectTagId,sortBy,order)
selectTagId <select id="selectTagId"></select>
sortBy [0:Text, 1:Value] - default:0
order[0:Ascending, 1:Descending] - default:0
Examples
sortingSelectBox("mySelectTagId",1,1) sortBy Value in Descending order
sortingSelectBox("mySelectTagId",1) sortBy Value in Ascending order
sortingSelectBox("mySelectTagId") sortBy Text in Ascending order
sortingSelectBox = (selectBoxId,sortBy,order) ->
   sortBy ?= 0
   order ?= 0
   sortVal = 0
   if order is 1 then sortVal = 2
   orderValLeft = -1 + sortVal
   orderValRight = 1 - sortVal
   selectBox = $("select#"+selectBoxId)
   options = $("select#"+selectBoxId+" option")
   selectedVal = selectBox.val()
   sortedOption = options.clone()
   options.empty().remove()
   switch sortBy
     when 0
       sortedOption.sort((left,right)->
         leftText = left.text.toLowerCase()
         rightText = right.text.toLowerCase()
         if leftText < rightText then return orderValLeft
         if leftText is rightText then return 0
         orderValRight
       )
     else
       sortedOption.sort((left,right)->
         leftVal = left.value
         rightVal = right.value
         if leftVal < rightVal then return orderValLeft
         if leftVal is rightVal then return 0
         orderValRight
       )
   selectBox.append(sortedOption)
   selectBox.val(selectedVal)
  
sortingSelectBox("country")

리다이렉트


// simulates similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");
// simulates similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

JQuery 데이터 타입


dataTypeString
Default: Intelligent Guess (xml, json, script, or html)
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:    "xml": Returns a XML document that can be processed via jQuery.
    "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
    "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
    "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
    "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "
=[TIMESTAMP]", to the URL unless the cache option is set to true.
    "text": A plain text string.
    multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.
/*
If you wish to use any of the meta-characters
( such as !"#$%&'()*+,./:;?@[]^`{|}~ ) as a literal part of a name,
you must escape the character with two backslashes: . For example,
if you have an an element with id="foo.bar", you can use the selector
$("#foo.bar").
*/

Session based tokens


If you are using session based tokens, you probably generate a secure token when generating the session, and store that token in the session. When a request comes back to the server, you check that the token is included in the request and compare it to what's in the session. If it's the same token, you accept the request, if not you reject it.
To use this token with jQuery, you need to make it available to javascript. You typically do this by adding it as a javascript variable.
var csrftoken = '<%= tokenvalue %>';
Next, the trick is to bind to the global ajaxSend event, and add the token to any POST request
$("body").bind("ajaxSend", function(elm, xhr, s){
if (s.type == "POST") {
xhr.setRequestHeader('X-CSRF-Token', csrf_token);
}
});

rails-3-1-and-jquery-ui-assets 설정


# http://stackoverflow.com/questions/6133818/rails-3-1-and-jquery-ui-assets
 $ cat app/assets/javascripts/application.js
    //= require jquery
    //= require jquery-ui
    $ cat app/assets/stylesheets/application.css
    /*
     *= require vendor
     *
     */
    $ cat vendor/assets/stylesheets/vendor.css
    /*
     *= requiretree ./jqueryui
     *
     */
    vendor/assets/ $ tree
     stylesheets
         vendor.css
             jqueryui
                      jquery-ui-1.8.13.custom.css
                      ...
     images
        jquery
ui
            ui-bgflat0aaaaaa40x100.png
            ...

Finally run this command:
    vendor/assets/images $ ln -s jquery_ui/ images
   

Get center


$(document).ready(function(){
  jQuery.fn.center = function () {
      this.css("top",$(window).height()/2-this.height()/2 + "px");
      this.css("left",$(window).width()/2-this.width()/2  + "px");
      return this;
  }
  $("#container").center();
 });
 

Multiple selector

$("#txt1, #txt2, #txt3").keyup(fn);

Jquery check CKEditor


$(this).data('initialForm', $(this).serialize());
to
$(this).data('initialForm', $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor));
And a similar change to line 4 from
if ($(this).data('initialForm') != $(this).serialize()) {
to
var formData = $(this).serialize() + '&' + FieldNameOfEditor + '=' + escape(ContentsOfEditor);
if ($(this).data('initialForm') != formData) {

Jquery Defer


(function() {
      function getScript(url,success){
        var script=document.createElement('script');
        script.src=url;
        var head=document.getElementsByTagName('head')[0],
            done=false;
        script.onload=script.onreadystatechange = function(){
          if ( !done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ) {
            done=true;
            success();
            script.onload = script.onreadystatechange = null;
            head.removeChild(script);
          }
        };
        head.appendChild(script);
      }
        getScript('http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js',function(){
            // YOUR CODE GOES HERE AND IS EXECUTED AFTER JQUERY LOADS
        });
    })();

Scroll to top   


var destination = $(‘#idToScrollTo’).offset().top;
$(‘html’).animate({scrollTop: destination},600);

CKEDITOR


config.toolbar = 'Modati'
config.toolbar_Modati = [['Bold', 'Italic', 'Underline','Strike', '-', 'RemoveFormat','-', 'Outdent','Indent','-','Blockquote','HorizontalRule', '-', 'JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','FontSize','TextColor','BGColor']]CKEDITOR.editorConfig = function( config )
{
    config.toolbar = 'MyToolbar';
 
    config.toolbar_MyToolbar =
    [
        { name: 'document', items : [ 'NewPage','Preview' ] },
        { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
        { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','Scayt' ] },
        { name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'
                 ,'Iframe' ] },
                '/',
        { name: 'styles', items : [ 'Styles','Format' ] },
        { name: 'basicstyles', items : [ 'Bold','Italic','Strike','-','RemoveFormat' ] },
        { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote' ] },
        { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
        { name: 'tools', items : [ 'Maximize','-','About' ] }
    ];
};
config.toolbar = 'Full';
 
config.toolbarFull =
[
    { name: 'document', items : [ 'Source','-','Save','NewPage','DocProps','Preview','Print','-','Templates' ] },
    { name: 'clipboard', items : [ 'Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ] },
    { name: 'editing', items : [ 'Find','Replace','-','SelectAll','-','SpellChecker', 'Scayt' ] },
    { name: 'forms', items : [ 'Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton',
 
         'HiddenField' ] },
    '/',
    { name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
    { name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','CreateDiv','-
 
        ','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','BidiLtr','BidiRtl' ] },
    { name: 'links', items : [ 'Link','Unlink','Anchor' ] },
    { name: 'insert', items : [ 'Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak','Iframe' ] },
    '/',
    { name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
    { name: 'colors', items : [ 'TextColor','BGColor' ] },
    { name: 'tools', items : [ 'Maximize', 'ShowBlocks','-','About' ] }
];
 
config.toolbar
Basic =
[
    ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','About']
];
CKEDITOR.editorConfig = function( config )
{
    config.extraPlugins = "customparagraph";
    config.toolbar = [ [ 'ThinyP' ] ]; // add other toolbars and keep in mid this can be overwritten in page which loads CKEditor
};
<script type="text/javascript">
//<![CDATA[
    // Replace the <textarea id="editor1"> with a CKEditor
    // instance, using default configuration.
    CKEDITOR.replace( 'editor1',
        {
            extraPlugins : 'customparagraph',
            toolbar :
            [
                [ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
                [ 'ThinyP' ]
            ]
        });
//]]>
</script>
in the main ckeditor config-file there is an option to disable automatic <p> inserts. try to change the value of CKConfig.EnterMode and CKConfig.ShiftEnterMode for example to 'br'.
config.enterMode = CKEDITOR.ENTER_BR
lostmorethanfive, lostbeetweenfourandfive, lostbeetweenthreeandfour, lostbeetweentwoandthree, lostbeetweenoneandtwo, lostbeetweenzeroandone, gainedbeetweenzeroandone, gainedbeetweenoneandtwo,gainedbeetweentwoandthree, gainedbeetweenthreeandfour, gainedbeetweenfourandfive,gainedbeetweenfiveandsix, gainedbeetweensixandseven,gainedmorethanseven


출처




by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

원하는 DIV 레이어를 간편하게 프린트 해주는 Div Print Jquery 스크립트 입니다.

이 스크립트는 두 개의 메소드를 포함하고 있습니다.
printdiv 메소드와 printdiviframe 메소드인데요.
두 출력 메소드 모두 Jquery 라이브러리가 필요하고,
print
diviframe 메소드는 JqueryUI 모듈도 필요로 합니다.
print
div는 새 창을 띄워서 바로 프린트 하고,
printdiviframe는 JqueryUI의 다이얼로그를 이용해 출력 미리보기를 제공합니다.

print_div_iframe-'Print Div Jquery Coffeescript, Javascript'

div 출력하는 커피스크립트나 자바스크립트가 필요하신 분은 가져다 쓰세요~

Div Print Jquery 스크립트 소스 다운로드



by


Tags : , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

모질라 파이어폭스에서 Ajax 한글 키 이벤트를 처리하는 Jquery,커피스크립트 코드입니다.

모질라 파이어폭스 Ajax. 한글 키 이벤트 처리.(Jquery Mozilla Force Keyup CoffeeScript module)

저는 주 브라우저로 모질라 파이어폭스를 사용합니다.
Ajax 모듈을 만드는데, 한글을 입력하면 못 알아듣더군요.
http://javascript.info/tutorial/keyboard-events에서 키 이벤트 체크를 해 봤습니다.
한글 키가 눌리면 Keydown(Keycode=229) 이벤트가 한 번만 발생하고,
Keyup 이벤트는 발생하지 않습니다.
중국어,일본어를 테스트 해보니 이 역시 같은 현상이군요.
한글과 다름없이 229키 코드가 딱 한번 발생합니다.
아마도 다른 블록형 문자 또한 같은 이벤트를 발생 시킬 거라 예상됩니다.
모질라에서 한글 키 이벤트를 부드럽게 처리하는 커피 스크립트 모듈을 만들었어요.
모질라 파이어폭스 이용자도 한글을 편하게 쓸 권리가 있으니까요.
필요하신 분은 마음껏 가져다 쓰세요.

커피스크립트 버전(Jquery Mozilla Force Keyup module  - Coffeescript version)



  
# Mozilla Force Keyup CoffeeScript module
# by 月風(http:://dorajistyle.pe.kr)
# How to use
# mozillaForceKeyup(”inputid”)
# in HTML.
# <input id=”input
id”>
mozillaForceKeyup = (targetId) ->
  if jQuery.browser.mozilla
    isIntervalRunning = null
    target = '#'+targetId
    $(target).bind 'keydown',(e) ->
      if e.which == 229
        forceKeyup = () ->
          $(target).trigger('keyup')
        if not isIntervalRunning
          isIntervalRunning = setInterval forceKeyup, 100

    $(target).bind 'blur',(e) ->
      if isIntervalRunning
        clearInterval isIntervalRunning
        isIntervalRunning = null



자바스크립트 버전(Jquery Mozilla Force Keyup module - Javascript version)



// Mozilla Force Keyup Javascript module
// by 月風(http:://dorajistyle.pe.kr)
// How to use
// mozillaForceKeyup(”inputid”)
// in HTML.
// <input id=”input
id”>

mozillaForceKeyup = function(targetId) {
var isIntervalRunning, target;
if (jQuery.browser.mozilla) {
isIntervalRunning = null;
target = '#' + targetId;
$(target).bind('keydown', function(e) {
var forceKeyup;
if (e.which === 229) {
forceKeyup = function() {
return $(target).trigger('keyup');
};
if (!isIntervalRunning) {
return isIntervalRunning = setInterval(forceKeyup, 100);
}
}
});
return $(target).bind('blur', function(e) {
if (isIntervalRunning) {
clearInterval(isIntervalRunning);
return isIntervalRunning = null;
}
});
}
};







by


Tags : , , , , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

It’s a simple code for ‘Sorting a select box’ using jquery, coffeescript

Sorting a Select box using Jquery, Coffeescript


I tried to find coffeescript code for sorting a select box.
But I didn’t find it.

Cause I just wrote own sorting select box code using jquery and coffeescript.

Copy and Paste below sorting select box coffeescript code and use it Freely.:D

Jquery, Coffeescript를 이용한 Select box 정렬 함수 입니다.

Simple Select Sorting Code (CoffeeScript Version)



 


#--Simple Select Sorting Method. (S3M:D)--

#sortingSelectBox(selectTagId,sortBy,order)

#selectTagId <select id="selectTagId"></select>

#sortBy [0:Text, 1:Value] - default:0

#order[0:Ascending, 1:Descending] - default:0

#Examples

#sortingSelectBox("mySelectTagId",1,1) sortBy Value in Descending order

#sortingSelectBox("mySelectTagId",1) sortBy Value in Ascending order

#sortingSelectBox("mySelectTagId") sortBy Text in Ascending order

#

#by JoongSeob Vito Kim - http://dorajistyle.pe.kr

sortingSelectBox = (selectBoxId,sortBy,order) ->

  sortBy ?= 0

  order ?= 0

  sortVal = 0

  if order is 1 then sortVal = 2

  orderValLeft = -1 + sortVal

  orderValRight = 1 - sortVal

  selectBox = $("select#"+selectBoxId)

  options = $("select#"+selectBoxId+" option")

  selectedVal = selectBox.val()

  sortedOption = options.clone()

  options.empty().remove()

  switch sortBy

    when 0

      sortedOption.sort((left,right)->

        leftText = left.text.toLowerCase()

        rightText = right.text.toLowerCase()

        if leftText < rightText then return orderValLeft

        if leftText is rightText then return 0

        orderValRight

      )

    else

      sortedOption.sort((left,right)->

        leftVal = left.value

        rightVal = right.value

        if leftVal < rightVal then return orderValLeft

        if leftVal is rightVal then return 0

        orderValRight

      )

  selectBox.append(sortedOption)

  selectBox.val(selectedVal)

 



  

Simple Select Sorting Code (JavaScript Version)


 


//Simple Select Sorting Method. (S3M:D)

//sortingSelectBox(selectTagId,sortBy,order)

//selectTagId <select id="selectTagId"></select>

//sortBy [0:Text, 1:Value] - default:0

//order[0:Ascending, 1:Descending] - default:0

//Examples

//sortingSelectBox("mySelectTagId",1,1) sortBy Value in Descending order

//sortingSelectBox("mySelectTagId",1) sortBy Value in Ascending order

//sortingSelectBox("mySelectTagId") sortBy Text in Ascending order

//

//by JoongSeob Vito Kim - http://dorajistyle.pe.kr

sortingSelectBox = function(selectBoxId, sortBy, order) {

var options, orderValLeft, orderValRight, selectBox, selectedVal, sortVal, sortedOption;

if (sortBy != null) {

sortBy;

} else {

sortBy = 0;

};

if (order != null) {

order;

} else {

order = 0;

};

sortVal = 0;

if (order === 1) {

sortVal = 2;

}

orderValLeft = -1 + sortVal;

orderValRight = 1 - sortVal;

selectBox = $("select#" + selectBoxId);

options = $("select#" + selectBoxId + " option");

selectedVal = selectBox.val();

sortedOption = options.clone();

options.empty().remove();

switch (sortBy) {

case 0:

sortedOption.sort(function(left, right) {

var leftText, rightText;

leftText = left.text.toLowerCase();

rightText = right.text.toLowerCase();

if (leftText < rightText) {

return orderValLeft;

}

if (leftText === rightText) {

return 0;

}

return orderValRight;

});

break;

default:

sortedOption.sort(function(left, right) {

var leftVal, rightVal;

leftVal = left.value;

rightVal = right.value;

if (leftVal < rightVal) {

return orderValLeft;

}

if (leftVal === rightVal) {

return 0;

}

return orderValRight;

});

}

selectBox.append(sortedOption);

return selectBox.val(selectedVal);

};



 

  
by 月風



by


Tags : , , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!

Perl에서 Jquery를 이용해 email 중복을 검사하는 방법입니다.

Perl에서 Jquery를 이용해 email 중복 검사 하기

-'Perl에서  Jquery를 이용한 email 중복체크 하기'

저는 이번에 Perl을 처음 건드려 봅니다.
'펄 세계엔, 한줄의 코드로 컴퓨터를 주므르는 고수들이 살고 있다!'
한참 전에 이런 소리를 들어 봤던거 같군요.
그때 든 생각은.
'한줄? 아! 디버깅하기 힘들겠구나.' 였어요.
인간 친화적이라기보다 기계 친화적인 언어라고 생각했었죠.
펄로 만들어진 PHP는 친숙하지만 Perl이라면 왠지 거리감이 느껴지는 언어였어요.
그런데 Perl에서도 요즘 흔히 쓰는 Jquery를 이용한 Ajax 구현이 가능합니다.
덕분에 조금 가까워 졌네요.:D


duplicate_test.html
<html><head/><body>
<INPUT maxLength=12 name="email" id="email" size="20"><br/>

<div id="duplicateResult"></div>
<script type="text/javascript" src="/rfo/jquery.js"></script>

<script type="text/javascript" src="/rfo/duplicate.js"></script>
</body></html>


duplicate.js
$(document).ready(function(){
  $("#email").keyup(function() {
    var email = $('#email').attr('value'); // get email
        if (email) { // values are not empty   
      $.ajax({
        type: "GET",
        url: "/cgi-bin/duplicate.pl", // URL of the Perl script
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "email=" + email,       
        // script call was not successful
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          $('div#duplicateResult').text("responseText: " + XMLHttpRequest.responseText
            + ", textStatus: " + textStatus
            + ", errorThrown: " + errorThrown);
          $('div#duplicateResult').addClass("error");
        }, // error
        // script call was successful
        // data contains the JSON values returned by the Perl script
        success: function(data){
          if (data.vacancy) { // script returned error
            $('div#duplicateResult').html("<span style='color:blue;font-size:14px;font-weight:bold;'>" + data.vacancy+"</span>");
            $('div#duplicateResult').addClass("vacancy");
          } // if
          else { // login was successful
            $('div#duplicateResult').html("<span style='color:red;font-size:14px;font-weight:bold;'>" + data.occupied+"</span>");
            $('div#duplicateResult').addClass("occupied");
          } //else
        } // success
      }); // ajax
    } // if
    else {
      $('div#duplicateResult').text("아이디를 입력해 주세요.");
      $('div#duplicateResult').addClass("error");
    } // else
    $('div#duplicateResult').fadeIn();
    return false;
  });
});


duplicate.pl

!/usr/bin/perl

use CGI;
use DBI;
use strict;
use warnings;
use rfoconfig;


read the CGI params

my $cgi = CGI->new;
my $email = $cgi->param("email");


connect to the database

my $dbh = DBI->connect("DBI:mysql:testDB:localhost","user","password");


check the username and password in the database

my $statement = qq{SELECT COUNT(*) FROM user WHERE email=?};
my $sth = $dbh->prepare($statement)  or die $dbh->errstr;
$sth->execute($email)  or die $sth->errstr;
my ($duplicatekey) = $sth->fetchrowarray;

my $json = ($duplicate_key) ?
  qq{{"occupied" : " $email는 이미 있는 아이디 입니다."}} :
  qq{{"vacancy" : "$email을 사용하실 수 있습니다."}};


return JSON string


"DBI:mysql:testDB:localhost","user","password"
우선 위 코드에서 testDB:localhost , user, password는 테스트 환경에 맞게 설정해 주세요.

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json;
아래 파일은 Document root/ 에 넣으세요.

  • Jquery.js (http://jquery.com 에서 다운로드 받으세요.)
  • duplicate.js
  • duplicate_test.html

아래 파일은 Document root/cgi-bin 에 넣으세요.

  • duplicate.pl


 

참고자료
Very simple login using Perl, jQuery, Ajax, JSON and MySQL

by 月風



by


Tags : , , , ,

  • 재미있게 읽으셨나요?
    광고를 클릭해주시면,
    블로그 운영에 큰 도움이 됩니다!