php - PHP - AJAX - 字段组数组 POST 值总是显示未定义的索引
问题描述
平台:WordPress
我有一组两个可克隆字段 name
和email
. 因此,当用户克隆时,他们将拥有一组name
和email
字段。
注意:这些字段是新添加到我的代码中的,并且 AJAX 可以在没有两个新添加字段的旧代码中正常工作。
ajax 代码总是给我一个未定义的索引name
错误。在debug.log文件中查看下面打印的确切错误
PHP 注意:未定义的索引:第 89 行.../cart-add-process-ajax.php 中的名称
第 89 行代码
下面的代码检查两个字段是否具有相同数量的数组项。所以稍后我可以将它们组合成一个关联数组。
此外,这些字段是选项,因此如果空 AJAx 仍应处理。
if (count($_POST[ 'name' ]) != count($_POST[ 'email' ])) {
// throw customers error
wp_send_json_error(__('Customer details are incorrect', 'online-shop'));
}
阿贾克斯
$('form.addtocartform').on('submit', function (e) {
e.preventDefault();
let names = [];
let emails = [];
$('input[name="name"]').each(function () {
names.push(this.value);
});
$('input[name="email"]').each(function () {
emails.push(this.value);
});
$.ajax({
method: 'POST',
dataType: 'json',
url: ajax_vars.ajax_url,
data: {
action: 'gs_add_to_cart',
nonce: ajax_vars.nonce,
group_id: $('#group_id').val(),
product: $('#product').val(),
qty: $('#qty').val(),
name: names,
email: emails,
product_option: $('#product_option').val(),
},
...
}
}
HTML
<form method="POST" id="gsAddToCart" class="addtocartform" action="">
<label for="product_option" class="gs-label">Options</label><select name="product_option" id="product_option" class="gs-select-box"><option value="">Select option</option><option value="0">Salty</option><option value="1">Sweet</option><option value="2">Bitter</option></select>
<label for="qty" class="gs-label">Qty.</label>
<input type="number" name="qty" id="qty" class="gs-number" min="1" step="1" value="1">
<!-- these fields in the div are clonable and here I have a problem -->
<div id="entry1" class="clonedInput gs-customer-fields">
<input class="gs-field" type="text" name="name[]" placeholder="Name">
<input class="gs-field" type="email" name="email[]" placeholder="Email">
</div>
<span class="gs-customer-delete" id="btnDel" disabled="disabled">delete</span>
<span class="gs-customer-add" id="btnAdd">add</span>
<input type="hidden" id="product" name="product" value="168">
<input type="hidden" id="group_id" name="group_id" value="298">
<input type="hidden" id="_gs_nonce" name="_gs_nonce" value="3676c059a6"><input type="hidden" name="_wp_http_referer" value="/products/id-adipisci-dolores-dicta/?group_id=298">
</form>
问题:
如何使用可克隆的表单字段处理 ajax,以便我可以在 PHP 中作为数组获取?
解决方案
推荐阅读
- python - 在 Python 中更改函数名称
- ios - 如何覆盖目标的字符串本地化文件中的字符串
- scala - WebSocket 缺少用于自定义数据类型的隐式消息流转换器 2.6
- php - Symfony 4 - 分页过滤器搜索问题
- python - 导入tensorflow.contrib.slim时如何解决UnicodeDecodeError
- android - 在一个地方更改 ID 会更改 Android XML 文件中其他地方的 ID
- c++ - 以下程序的意外输出
- react-native - 执行“react-native link realm”时出错
- c++ - 如何在 C++ 中将一个类的实例完全重新分配给同一类的另一个实例(然后删除原始对象)?
- python - 用于检查文件夹中的更改并复制到另一个文件夹中的 Bash 文件