繁体   English   中英

使用jQuery提交动态创建的复杂表单而无需刷新

[英]Submitting dynaically created complex form with jQuery without refresh

如何将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>

如果您的表单格式正确,则只需将jQuery的serialize()函数post()函数一起使用。 它将在表格中为您构建一个参数查询字符串。

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

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

连载

.serialize()方法以标准的URL编码表示法创建文本字符串。 它对表示一组表单元素的jQuery对象进行操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM