【发布时间】:2019-12-28 22:36:23
【问题描述】:
我的 JSON 数组有问题。这是我的 Ajax 代码(我上传文件 excel 并将其返回为 JSON。然后将 Json 转换为字符串并保存到 myDb):
function exportExcelToTable() {
$('#upload-excel-convert').change(function (e) {
let file = $(this).prop('files')[0];
let formData = new FormData();
formData.append("file",file);
$("#js-render-btn-see-excel").html('');
$('#js-table-excel tbody').html('');
$.ajax({
method:'POST',
url: '/order/excel/read-file',
data: formData,
contentType: false,
processData: false,
dataType:'json',
success(data) {
let $data = $('input[name="order[sizeFile]"]');
for (let i = 1; i < data.length; i++) {
$data.val(JSON.stringify(data[i]));
console.log(data[i]);
}
}
});
})
}
这是要返回的 Json console.log(data[i])。
[["XS ", "Nam", null, null, null, 20],
["S", null, 13, null, null, 35],
["M", null, 12, null, null, 12]
]
而我的输入值只是返回最后一个数组
<input type="hidden" name="order[sizeFile]" value="["M";,null,12,null,null,12]">
我想要这样的输入值:
<input type="hidden" name="order[sizeFile]" value="[["XS ", "Nam", null, null, null, 20],["S", null, 13, null, null, 35],["M", null, 12, null, null, 12]]">
我该如何解决这个问题?谢谢。
P/s对不起我的英语。
UPDATE
我正在更新我的代码。
function exportExcelToTable() {
$('#upload-excel-convert').change(function (e) {
let file = $(this).prop('files')[0];
let formData = new FormData();
formData.append("file",file);
$("#js-render-btn-see-excel").html('');
$('#js-table-excel tbody').html('');
$.ajax({
method:'POST',
url: '/order/excel/read-file',
data: formData,
contentType: false,
processData: false,
dataType:'json',
success(data) {
let $data = $('input[name="order[sizeFile]"]');
let list;
for (let i = 1; i < data.length; i++) {
list += JSON.stringify(data[i]);
$data.val(list);
console.log(data[i]);
}
}
});
})
}
没错,但我的输入显示 undefined 的值。
<input type="hidden" name="order[sizeFile]" value="undefined[["XS ", "Nam", null, null, null, 20],["S", null, 13, null, null, 35],["M", null, 12, null, null, 12]]">
【问题讨论】:
-
这是你想要的吗?
-
JS 数组是从 0 开始的。
-
@sid 是的。这就是我想要的。 :))
-
我更改了
let i = 0。但它直到相同。 @DaveNewton -
尝试构建你的字符串然后设置
val,而不是每次通过循环设置它。
标签: javascript jquery arrays json