Ajax发送多个输入

  • 本文关键字:Ajax html django ajax
  • 更新时间 :
  • 英文 :


我有一个名为personals的html输入字段。我使用[],这样我就可以在同一个名字上有多个输入并发布它。在我使用普通的提交表单之前。我得到了它在我的Django后端与getlist('personal[]')

作为信息:代码不完整。只显示最重要的行。

之前的html代码
<input type="text" name="personals[]" id="personals[]" placeholder='Email'> 
<input type="text" name="personals[]" id="personals[]" placeholder='Phone'>

My view before

def build(request):
if request.user.is_authenticated:
if request.method == 'POST':
name = request.POST.get('name')
personals = request.POST.getlist('personals[]')

现在我使用Ajax提交它,而不需要重新加载页面。它不工作了personals[]因此我也改变了personals只是没有括号。

问题是,personal只包含第一个输入。但不是所有其他的。

使用相同的输入名称(在本例中为personals)非常重要,因为我使用了一些动态输入字段,用户可以在其中添加更多字段。因此,我不想将名称更改为例如personals1personals2

我的html代码现在

<input type="text" name="personals" id="personals" placeholder='Email'> 
<input type="text" name="personals" id="personals" placeholder='Phone'>

My view now

def build(request):
if request.user.is_authenticated:
if request.method == 'POST':
name = request.POST.get('name')
personals = request.POST.get('personals')

My ajax function

$.ajax({
type: 'POST',
cache: false,
url: "{% url 'creator:build' %}",
data: {
name:$('#name').val(),
personals:$('#personals').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
})

你的问题可能是你在'个人'中有多个值,但你只在你的视图中得到一个,你应该尝试使用request.POST.getlist('personals[]')

作为一个更普遍的观点,你似乎在你的输入中收集电子邮件和电话数据——你的输入名称应该是'email'和'phone',你可以使用Django表单来更容易地渲染和处理这些输入。如果用户可以创建额外的字段或表单,那么这些可以由Django的表单或表单集来处理。

我找到了解决方案:

var personals = [];
$('input[name="personals[]"]').each(function() {
personals.push(this.value);
});

这里是ajax:

$.ajax({
type: 'POST',
cache: false,
url: "{% url 'creator:build' %}",
data: {
name:$('#name').val(),
personals: personals,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
})

,最后是视图:

def build(request):
if request.user.is_authenticated:
if request.method == 'POST':
name = request.POST.get('name')
personals = request.POST.getlist('personals[]')

发送2个或更多的输入具有相同名称的使用ajax

最新更新