如何在新窗口中创建HTML表单

如何在新窗口中创建HTML表单

我有以下功能:

// open a new window. Create and submit form
function createSubmitForm(response) {
    var external = window.open('about:blank', 'external');
    var doc = external.document;
    var body = $('body', doc);

    // create a new form element
    var form = $("<form id='authForm'></form>");
    // set the form's attributes and add to iframe
    form.attr("action", response.action)
        .attr("method", response.method);
    form.appendTo(body);

    // create form elements;
    for (var i = 0, len = response.fields.length; i < len; i++) {
        var field = response.fields[i];

        if (field.name != "") {
            $("<input type='hidden'/>")
                .attr("name", field.name)
                .attr("value", field.value)
                .appendTo(form);
        }
    }
    // submit the form
    form.submit();
}


当我尝试执行它时,在form.appendTo(body)处出现“未指定的错误”。

我在这里可能做错了什么?

最佳答案

尝试这个:

请注意,您的服务器http://localhost/some-blank-page-on-your-server.php上必须有空白页

<!DOCTYPE html>
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup,
  menu, nav, section { display: block; }
</style>
</head>
<body>

</body>
<script>
(function($) {
$(function() {
    // open a new window. Create and submit form
    function createSubmitForm(response) {
        var external = window.open('http://localhost/some-blank-page-on-your-server.php', 'external');
setTimeout(function() {
        var doc = external.document;
        var body = $('body', doc);

        // create a new form element
        var form = $("<form id='authForm'></form>");
        // set the form's attributes and add to iframe
        form.attr("action", response.action)
            .attr("method", response.method);


        // create form elements;
        for (var i = 0, len = response.fields.length; i < len; i++) {
            var field = response.fields[i];

            if ( field.name !== "" ) {
                $("<input type='text'/>")
                    .attr("name", field.name)
                    .attr("value", field.value)
                    .appendTo(form);
            }
            $("<input type='submit' value='submit' />").appendTo(form);
        }
        // submit the form
        form.submit();

        body.append(form);
}, 1000);
    }

    createSubmitForm({
      action: 'http://www.example.com',
      method: 'get',
      fields: [{
        name: 'field1',
        value: 'some value'
      }]
    });
});
})(jQuery);
</script>
</html>

关于javascript - 如何在新窗口中创建HTML表单,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6835422/

10-11 11:45