动态创建和提交表单

问题描述:

jQuery 中有没有一种方法可以即时创建和提交表单.

Is there a way in jQuery to create and submit a form on the fly.

类似于下面的内容.

<html>
    <head>
    <title> Title Text Goes Here </title>
    <script src="http://code.jquery.com/jquery-1.7.js"></script>
    <script>
        $(document).ready(function(){alert('hi')});
        $('<form/>').attr('action','form2.html').submit();
    </script>
    </head>
    <body>

        Content Area

    </body>
    </html>

这应该有效还是有其他方法可以做到这一点?

Is this supposed to work or there is a different way to do this?

您的代码有两处错误.第一个是您包含了 $(document).ready(); 但没有包装使用它创建元素的 jQuery 对象.

There were two things wrong with your code. The first one is that you included the $(document).ready(); but didn't wrap the jQuery object that's creating the element with it.

第二个是您使用的方法.jQuery将在替换您要创建的元素时替换选择器(或通常将选择器)替换为您要创建的元素时创建任何元素.然后你只需将它附加到正文并提交即可.

The second was the method you were using. jQuery will create any element when the selector (or where you would usually put the selector) is replaced with the element you wish to create. Then you just append it to the body and submit it.

$(document).ready(function(){
    $('<form action="form2.html"></form>').appendTo('body').submit();
});

这是 正在运行的代码.在这个例子中,它没有自动提交,只是为了证明它会添加表单元素.

Here's the code in action. In this example, it doesn't auto submit, just to prove that it would add the form element.

这是自动提交的代码.效果很好.Jsfiddle 将您带到 404 页面,因为form2.html"显然不在其服务器上.

Here's the code with auto submit. It works out fine. Jsfiddle takes you to a 404 page because "form2.html" doesn't exist on its server, obviously.