连接两个AJAX请求返回到1个数组



下面是我的代码。我有两个ajax请求,从包含相同信息的两个独立列表中提取数据。当他们在我的成功函数中填充我的表时,它会发布两个单独的表,而不是一个,但它包含了我想填充到表中的所有信息。

如何将返回连接到一个数组中以发布到表中?

$(function(){
window.addEventListener('load', function(){
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree";
var fullUrl1 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree";
$.ajax({
url: fullUrl,
type: "GET",
headers: {
"accept":"application/json; odata=verbose"
}, 
success: onSuccess,
error: onError
});
$.ajax({
url: fullUrl1,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});

function onSuccess(data) {
var objItems = data.d.results;
var tableContent = '<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' + '<td><strong>Age</strong></td>' + '<td><strong>Position</strong></td>' + '<td><strong>Office</strong></td>' + '<td><strong>Education</strong></td>' + '<td><strong>Degree</strong></td>' +'</tr></thead><tbody>';
for (var i = 0; i < objItems.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + objItems[i].Title  + '</td>';
tableContent += '<td>' + objItems[i].Age + '</td>';
tableContent += '<td>' + objItems[i].Position + '</td>';
tableContent += '<td>' + objItems[i].Office + '</td>';
tableContent += '<td>' + objItems[i].Education + '</td>';
tableContent += '<td>' + objItems[i].Degree + '</td>';
tableContent += '</tr>';
}
$('#employees').append(tableContent);
}
function onError(error) {
alert('Error');
}
});
});

这里有一个使用fetch()和promise的公式。(干编码,所以可能有愚蠢的错误。(

编辑:添加了添加到所有结果中的source参数。

function loadData(source, url) {
return fetch(url, { headers: { accept: "application/json; odata=verbose" } }) // make request
.then((r) => {
if (!r.ok) throw new Error("Failed: " + url);  // Check for errors
return r.json();  // parse JSON
})
.then((data) => data.d.results) // unwrap to get results array
.then((results) => {
results.forEach((r) => (r.source = source)); // add source to each item
return results;
});
}
window.addEventListener("load", function () {
Promise.all([
loadData("EmployeeInfo", _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree"),
loadData("Employee2", _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree"),
])
.then(([r1, r2]) => {
const objItems = r1.concat(r2);
var tableContent =
'<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' +
"<td><strong>Age</strong></td>" +
"<td><strong>Position</strong></td>" +
"<td><strong>Office</strong></td>" +
"<td><strong>Education</strong></td>" +
"<td><strong>Degree</strong></td>" +
"<td><strong>Source</strong></td>" +
"</tr></thead><tbody>";
for (var i = 0; i < objItems.length; i++) {
tableContent += "<tr>";
tableContent += "<td>" + objItems[i].Title + "</td>";
tableContent += "<td>" + objItems[i].Age + "</td>";
tableContent += "<td>" + objItems[i].Position + "</td>";
tableContent += "<td>" + objItems[i].Office + "</td>";
tableContent += "<td>" + objItems[i].Education + "</td>";
tableContent += "<td>" + objItems[i].Degree + "</td>";
tableContent += "<td>" + objItems[i].source + "</td>";
tableContent += "</tr>";
}
$("#employees").append(tableContent);
})
.catch((err) => {
alert("Error: " + err);
console.error(err);
});
});

编辑:

对于任意数量的数据源,您可以进行

Promise.all([
loadData("A", ...),
loadData("B", ...),
loadData("C", ...),
loadData("D", ...),
loadData("E", ...),
])
.then((arrays) => {
const objItems = arrays.reduce((a, b) => a.concat(b), []);
// ...

我现在可以想出两种不使用promise的方法。1您可以使用闭包来捕获响应。2全局变量

我更喜欢第一种方法,因为它看起来更易于维护和重用。

function requestCounter() {

return (function l2(){

var data = [];

var totalRequest = 0;

return (function l3 (){

return {

get : function (){

return {data:data,totalRequest}

},add : function(responseData){

totalRequest += 1

data = data.concat(responseData)
}
}
})()

})()

}
var requestCounter = requestCounter()
var tempData1 = [
{Title :"T1",Age :"12" },
{Title :"T2",Age :"13" }
]
var tempData2 = [
{Title :"T3",Age :"125" },
{Title :"T4",Age :"133" }
]
function onSuccess(data) {
//replace this with your data.d.results
var objItems = data;

requestCounter.add(objItems);

var totalData = requestCounter.get();

if(totalData.totalRequest > 1) {
var tableContent = '<table id="employeeTab" style="width:100%" border="1 px"><thead><tr><td><strong>Name</strong></td>' + '<td><strong>Age</strong></td>' + '<td><strong>Position</strong></td>' + '<td><strong>Office</strong></td>' + '<td><strong>Education</strong></td>' + '<td><strong>Degree</strong></td>' +'</tr></thead><tbody>';
for (var i = 0; i < totalData.data.length; i++) {
tableContent += '<tr>';
tableContent += '<td>' + totalData.data[i].Title  + '</td>';
tableContent += '<td>' + totalData.data[i].Age + '</td>';

tableContent += '</tr>';
}

}

console.log(tableContent);
}
//first ajax call
onSuccess(tempData1);
///second ajax call
onSuccess(tempData2);


有了承诺,你可以参考这个链接。当所有AJAX请求完成时

请考虑以下代码。

$(function() {
var myData = [];
window.addEventListener('load', function() {
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('EmployeeInfo')/items?$select=Title,Age,Position,Office,Education,Degree";
var fullUrl1 = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Employee2')/items?$select=Title,Age,Position,Office,Education,Degree";
$.ajax({
url: fullUrl,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
$.ajax({
url: fullUrl1,
type: "GET",
headers: {
"accept": "application/json; odata=verbose"
},
success: onSuccess,
error: onError
});
function onSuccess(data) {
$.each(data.d.results, function(l, v) {
myData.push(v);
});
refreshTable();
}
function initTable(hdrs) {
var t = $("<table>", {
id: "employeeTab"
}).css({
width: "100%",
border: "1"
});
$("<thead>").appendTo(t);
var r = $("<tr>").appendTo($("thead", t));
$.each(hdrs, function(i, h) {
$("<th>").html(h).appendTo(r);
});
return t;
}
function refreshTable() {
var tableContent;
if ($("#employeeTab").length == 0) {
tableContent = initTable(["Name", "Age", "Position", "Office", "Education", "Degree"]);
tableContent.appendTo("#employees");
} else {
tableContent = $("#employeeTab");
}
var tBod = $("tbody", tableContent);
tBod.html("");
$.each(myData, function(k, v) {
var row = $("<tr>").appendTo(tBod);
$.each(v, function(j, item) {
$("<td>").html(item).appendTo(row);
});
});
}
function onError(error) {
alert('Error');
}
});
});

我们可以在函数之外使用一个变量myData来包含所有数据。类似于全局变量。

为了便于使用,我将这些步骤分解为各自的功能。

相关内容

  • 没有找到相关文章

最新更新