post/get/put等方式跳轉界面方法封裝(javascript)

衆所周知,js跳轉新頁面只支持get傳參(window.open,a標籤等),但是有些長參數傳遞不過去,下面就封裝一個條抓方法:

var goToOtherPage = {
    params: {},
    form: null,
    config: {},
    create: function() {
        document.body.appendChild(this.form = document.createElement('form'));
        this.form.setAttribute('act', this.config.action);
        this.form.setAttribute('method', this.config.method);
        this.form.setAttribute('target', this.config.target);
        return this;
    },
    init: function(config) {
        config = config || {};
        
        this.config = {
            action: config.action || '?',
            method: config.method || 'post',
            target: config.target || '_self'
        }
        
        return this;
    },
    bind: function(data) {
        if (typeof data !== 'object') {
            return this;
        }
        
        this.params = {};

        for (var key in data) {
            switch(typeof data[p]) {
                case 'object':
                    this.params[key] = JSON.stringify(data[key]);
                    break;
                default:
                    this.params[key] = data[key];
                    break;
            }
        }

        return this;
    },
    send: function() {
        if (!this.params) {
            return this;
        }
        
        this.create();

        for (key in this.params) {
            var tempInput = document.createElement('input');
            tempInput.setAttribute('type', 'hidden');
            tempInput.setAttribute('name', key);
            tempInput.setAttribute('value', this.params[key]);
            this.form.appendChild(tempIput);
        }
        
        this.form.submit();
        this.clear();
        return this;
    },
    clear: function() {
        var inputs = this.form.childNodes;

        for (var i = inputs.length - 1; i > -1; i--) {
            this.form.removeChild(inputs[i]);
            inputs[i] && (inputs[i] = null);
        }

        document.body.removeChild(this.form);
        this.form = null;
    }
}

調用示例:

goToOtherPage.init({act: 'txt.php',target: '_blank'}).bind({text:'hello world'}).send();

另iframe + goToOtherPage方法可以實現當前界面塊加載不同界面,示例代碼如下:

html:

<iframe name="child-page" src="" style="border: 0;">

js:

goToOtherPage.init({act: 'txt.php',target: 'child-page'}).bind({text:'hello world'}).send();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章