请帮我为我的Ajax创建一个动态数组。
我想在将动态数组附加到我的UI之前将动态数组传递给我的函数appendOption()。请帮我。感谢。
CSVFile.addEventListener('change', function (e) {
var array0 = [];
var array1 = [];
var array2 = [];
var array3 = [];
var array4 = [];
var array5 = [];
parseCSV.loadFile(file, function () {
var sheet = parseCSV.getSheet();
var columnCount;
sheet.forEach(function (el, i) {
columnCount = el.length;
array0.push(el[0]);
array1.push(el[1]);
array2.push(el[2]);
array3.push(el[3]);
array4.push(el[4]);
array5.push(el[5]);
});
//This is my ajax
var myRoot = window.location.origin + "/";
$.ajax({
url: myRoot + 'Payslip/GetDataFromAppend',
type: 'GET',
contentType: "application/json; charset=utf-8",
//data: JSON.stringify({ id: $this }),
async: true,
success: function (data) {
for (var i = 0; i < columnCount; i++) {
$(wrapper).append(appendOption(data, array0));
}
}
});
//This is my function
//For Append from ajax
var appendOption = function (data, arrayData) {
var appendfor = '<div class="form-group"><label class="col-sm-4 control-label"><input type="text" class="form-control" value="' + arrayData+ '"/></label><div class="col-sm-7">' +
'<select class="form-control" asp-for="PayslipID" asp- items="ViewBag.PayslipID" data- val="true" data- val - required="The Payslip ID field is required." id= "PayslipID" name= "PayslipID" >';
for (var i = 0; i < data.length; i++) {
console.log(data[i].value);
appendfor += '<option value="' + data[i].value + '">' +
data[i].value
+ '</option>';
}
appendfor += '</select ></div ></div > ';
return appendfor;
}
}
});
});
});
//For Append from ajax
var appendOption = function (data, txtData) {
var appendfor = '<div class="form-group"><label class="col-sm-4 control-label"><input type="text" class="form-control" value="' + txtData + '"/></label><div class="col-sm-7">' +
'<select class="form-control" asp-for="PayslipID" asp- items="ViewBag.PayslipID" data- val="true" data- val - required="The Payslip ID field is required." id= "PayslipID" name= "PayslipID" >';
for (var i = 0; i < data.length; i++) {
console.log(data[i].value);
appendfor += '<option value="' + data[i].value + '">' + data[i].value + '</option>';
}
appendfor += '</select ></div ></div > ';
return appendfor;
}
&#13;
答案 0 :(得分:0)
我可以认为columnCount是undefined.so skiping it.Use java script hoisting。即,在顶部声明函数然后调用函数。[https://www.w3schools.com/js/js_hoisting.asp]希望这段代码snipet很有用。
let ar1 = [1,2,3];
let ar2 = [4,5,8];
let ar3 = [6,7,8];
//use hoisitng so declare thhe function on top
var appendOption = function (data, arrayData) {
console.log("data is "+data+" array data is "+arrayData)
}
//making mock server data - reprensenting ajax
let data = [1,2,3]
for (let i in data) {
appendOption(data[i],ar1[i]); //executes until the lenght of data
appendOption(data[i],ar2[i]);
appendOption(data[i],ar2[i]);
}
&#13;