通过ajax将表单发布到顶部窗口

时间:2014-01-31 13:15:29

标签: javascript ajax forms

我必须通过ajax模拟发布表单,但是能够自定义来自服务器的响应,这里有几行来自我的代码:

helper.parseFormData = function parseFormData(form) {
    var json = {};
    form.find("[name]").each(function() {
        var _name = $(this).attr("name")
            , _value = $(this).attr("value");

        if (json[_name] == undefined) {
            json[_name] = _value;
        }
    });
    return json;
};
helper.submitForm = function submitForm(form, callback) {
    var _data = helper.parseFormData(form)
        , _url = form.attr("action")
        , _type = form.attr("method");

    $.ajax({
        type: _type,
        url: _url,
        data: _data,
        success: function(content, p2, p3) { callback(content); },
        error: function(p1, p2, p3) { callback(null); }
    });
};

// wait for iframe (step #3) is loaded to put form submit handler
(function ProcessChildFrame() {
    var _attempts = 100;
    (function fnWait() {
        setTimeout(function() {
            var _form = _iframe.get(0).contentWindow.document.getElementById("checkout");
            if (_form) {
                var step3Form = $(".mm-frame-wrapper iframe").contents().find("form");
                step3Form.on("submit", function () {
                    helper.submitForm(step3Form, function(html) {
                        // html contains response from server

                        /* if response contains errors - write result into iframe (this part is working good)
                            else - write result into top parent window (this part is working not as expected) */
                        var _doc = window.document;
                        if (html) {
                            if (/id=\"error\"/.test(html)) {
                                html = html.replace("</head>", helper.getHideStyleString() + "</head>");

                                ProcessChildFrame(); // update submit handlers

                                // iframe document
                                _doc = _iframe.get(0).contentWindow.document;
                            }

                            _doc.open('text/html', 'replace');
                            _doc.write(html);
                            _doc.close();

                                                    // how to force scripts execution???

                        }
                    });
                    return false;
                });
            }
            else if (_attempts--) {
                fnWait();
            }
        }, 100);
    })();
})();

所以我基本上模拟了<form method="POST" target="_top" >行为 - 但是使用了ajax。有什么想法吗?

更新#1: 好吧,我发现我的代码几乎正常工作...我现在唯一的问题 - 当我做document.write()时 - 脚本没有执行....任何想法如何触发{{{{{{{ 1}} ???

0 个答案:

没有答案