使用jQuery动态创建复杂表单而不刷新

时间:2012-09-07 00:17:43

标签: javascript jquery html forms

如何将jQuery.post用于复杂的动态创建表单?

这是我的代码:

<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="/media/css/screen.css" />
<script>
var id = 0;

function removeField(fieldId) {
    $('#field_'+fieldId).hide();
}

function addField(fieldType) {
    var html = '<tr id="field_'+id+'"><td><input type="button" value="X" onclick="removeField('+id+')"/></td><td><input type="hidden" name="field_'+id+'_type" value="char"><input name="field_'+id+'_name" type="text" value="" /></td><td>'+fieldType+'</td><td><input type="checkbox"  name="field_'+id+'_unique" /></td>';
    switch (fieldType) {
        case 'char':
            html += '<td> <strong>Max length:</strong> <input name="field_'+id+'_max_length" type="text" value=""/></td>';
            break;
        case 'foreignkey':
            html += '<td> <strong>Related model:</strong> <input name="field_'+id+'_related_model" type="text" value=""/></td>';
            break;
    }
    html += '</tr>';
    $('#fields').append(html);
    id += 1;
    $('#fields').show();
}
</script>
</head>
<body>

<form action="/create_model/" method="post">

<strong>Model name:</strong> <input type="text" name="name" /><br/>
<table id="fields"><th style="width:10px;"></th><th style="width:100px;">Name</th><th style="width:50px;">Type</th><th style="width:25px;">Unique</th><th></th></tr></table>
<strong>Add field:</strong> <input type="button" value="Char" onclick="addField('char');" />
<input type="button" value="ForeignKey" onclick="addField('foreignkey');"/><br/>
<input type="submit" value="Create Model" />
</form>

</body>
</html>

1 个答案:

答案 0 :(得分:0)

如果表单格式正确,您只需将jQuery's serialize() functionpost() function一起使用即可。它将在表单中为您构建参数的查询字符串。

var content = $("#formElement").serialize();

$.post('server.php',{'data':content},function(response){
  // request success callback
});
  

序列化

     

.serialize()方法使用标准的URL编码表示法创建文本字符串。它在表示一组表单元素的jQuery对象上运行。