[jQuery] ajaxForm 구현

JavaScript/jQuery 2012. 7. 23. 00:31

사실 ajax를 이용하는게 아니라 예전부터 많이 사용하던 iframe을 이용하여 화면 깜빡임을 없애는 방식이다.


/**

 * form을 ajax로 전송한다. (파일 포함)

 */

$.fn.ajaxForm = function(handler) {

    var $this = $(this);

    if ( $this[0] && $this[0].tagName.toUpperCase() == "FORM" ) {

        //랜덤한 수를 출력

        var ranNumber = Math.floor(Math.random() * 10000) + 1;

        var strId = "";

        strId += "SEED";

        strId += "_";    

        strId += (new Date()).getTime();

        strId += "_" + ranNumber;


        $this.attr("target", strId);    

        $("<iframe id=\"" + strId + "\" name=\"" + strId + "\" />")

            .hide()

            .appendTo($this.parents("body"))

            .load(function() {

                var that = this;


                if ( $.type(handler) == "function" ) {

                    var result = $.parseJSON(window.frames[strId].document.body.innerHTML);

                    if ( result == undefined || result == null || result == "" ) {

                        result = {

                            success : false,

                            message : "결과가 존재하지 않습니다."

                        };

                    }

                    handler(result);

                }

            });

    }//if ( $this[0] && $this[0].tagName.toUpperCase() == "FORM" ) {


    return $this;

};


사용방법

(function($, exports) {$(document).ready(function() {

////////////////////////////////////////////////////////////////////////////////////

$("#myform").ajaxForm(function(result) {

    if ( result && result.success == true ) {

        alert(result.message);

    }

});

////////////////////////////////////////////////////////////////////////////////////

});})(jQuery, window);



참고 : http://hanjiq.egloos.com/2373084 

posted by 뚱2