【问题标题】:Use jquery variable and loop in Ajax post data在 Ajax 发布数据中使用 jquery 变量和循环
【发布时间】:2017-06-29 21:09:05
【问题描述】:

我真的不知道如何使用 Ajax 发布数据功能,但我正在使用一些免费的简单文件并尝试对其进行一些调整。

我要更改的简单代码部分是:

post_data = {
'clcon_user_name'       : $('input[name=name]', clientConParent).val(),
'clcon_user_lastname'   : $('input[name=lastname]', clientConParent).val(),
'clcon_user_email'  : $('input[name=email]', clientConParent).val(),
'clcon_phone_number'    : $('input[name=phone]', clientConParent).val(),
'clcon_msg'         : $('textarea[name=message]', clientConParent).val(),
'pro_mailto'    : $('input[name=promailto]', clientConParent).val()
};

我想让它动态化,这样它就会循环遍历我表单上的字段并以这种格式获取它们: 'npf_{字段名称atrr}' : $('input[name={字段名称atrr}]', theForm).val(), 用于 post_data(用于 Ajax $.post(... 函数)。

我试过了:

post_data = {
$("input, textarea, select", theForm).each(function(){
'\'npf_$'+$(this).attr('name')'\'' : $('input[name='++$(this).attr('name')+']', theForm).val(),
});
};

没用,也试过了:

post_data = {
$("input, textarea, select", theForm).each(function(){
var theName = $(this).attr('name');
'npf+theName' : $('input[name='+theName+']', theForm).val(),
});
};

没用,也试过了:

post_data = {
$("input, textarea, select", theForm).each(function(){
var theName = $(this).attr('name');
'npf+theName' : $('input[name='+theName+']', theForm).val(),
});
};

我知道我一定做错了几件事...我可以使用一些“傻瓜”的解释感觉我是初学者。

【问题讨论】:

标签: jquery ajax loops variables


【解决方案1】:

创建一个空对象,然后遍历表单以设置该对象的属性。

post_data = { };

$("input, textarea, select", theForm).each(function(){
    var theName = $(this).attr('name');
    post_data['npf_' + theName] = $(this).val();
});

【讨论】:

  • 出于某种原因,如果我像您建议的那样使用post_data['npf_' + theName] = $(this).val();,它不起作用,但如果我使用post_data['npf_' + theName] = $('input[name='+theName+']', theForm).val(),它会起作用。你能说出原因吗?
  • 每个循环内部this 绑定到当前的HTML 元素,如果它可以获取元素的名称,它也应该能够获取值。我怀疑还有其他问题,但如果没有看到更多代码或您遇到的错误,我无法判断是什么。这是一个显示它工作的示例:jsfiddle.net/jk8y0916/2
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多