我是淘汰赛的新手,我通过比较两个数组值来创建数据表。我的问题是,我使用外部JSON数据显示表数据。我将尝试使用此方法来比较两个数组,即从外部JSON给出的数组值。他们没有获得外部JSON的数据。如何使用外部JSON显示我们的表。我的样本代码是,
我的剧本
jQuery(function($){
var ListSortModel = function () {
var self = this;
self.first = ko.observableArray([
{ "id": 101, "rank": 5},
{ "id": 103, "rank": 1},
{ "id": 102, "rank": 6},
{ "id": 105, "rank": 2}
]);
self.second = ko.observableArray();
var currency = function(data) {
var self = this;
self.id = ko.observable(data.id);
self.rank = ko.observable(data.rank);
}
$.ajax({
url: "../2x-compare/data.php",
data: '{}', // parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8", // posting JSON content
dataType: "JSON",
success: function (Result) {
var mappedCurrencies =
$.map(Result.d, function(item){
return new currency(item); // Here, $.map will just new up a new currency,
// using the constructor argument to set fields
});
self.second(mappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
var a = self.first();
var b = self.second();
console.log(a);
console.log(b);
var totallen = 0;
if(a.length >= b.length){
totallen = a.length;
}else{
totallen = b.length;
}
for(var i=0;i<a.length;i++)
for(var k=0;k<b.length;k++)
if(a[i].id == b[k].id) {
if(a[i].rank > b[k].rank){
b[k].img = 0;
}else if(a[i].rank < b[k].rank){
b[k].img = 1;
}else if(a[i].rank == b[k].rank){
b[k].img = 2;
}
a.splice(i,1);
i--;
break;
}
a = a.concat(b);
for(i=0;i<totallen;i++){
if(a[i].img == undefined){
if(a[i].rank < totallen){
a[i].img =0;
}else if(a[i].rank > totallen){
a[i].img = 1;
}else if(a[i].rank == totallen){
a[i].img = 2;
}
}
}
a.sort(function(obj1,obj2) {
return obj1.id > obj2.id;
});
/* compared array values stored in third array */
self.third = ko.observableArray(a);
temp = 1;
self.addImg = function(index) {
var id = self.third()[index].rank;
if(self.third()[index].img == 1){
return 'downImg';
}else if(self.third()[index].img == 0){
return 'upImg';
}
else if(self.third()[index].img == 2){
return;
}
};
self.addClass = function(index) {
var id = self.third()[index].rank;
if(self.third()[index].img == 1){
return 'redClass';
}else if(self.third()[index].img == 0){
return 'blueClass';
}
else if(self.third()[index].img == 2){
return;
}
};
/* sorting based on rank after display third array*/
self.SortbyRank = function() {
self.third().sort(function(obj1,obj2) {
//alert(obj1.rank + ">" +obj2.rank);
return obj1.rank > obj2.rank;
});
self.third.valueHasMutated();
}
window.setInterval(function() {
self.SortbyRank();
}, 5000);
};
ko.applyBindings(new ListSortModel());
});
data.php
{ d: [
{ "id": 101, "rank": 5},
{ "id": 102, "rank": 6},
{ "id": 106, "rank": 1},
{ "id": 103, "rank": 4},
{ "id": 104, "rank": 2},
{ "id": 105, "rank": 3}
]
}
这是我的示例代码,这将只显示第一个数据,我想比较第三个变量中的第一个和第二个数据显示。但他们没有从ajax获取第二个数据,他们应该只显示表中的第一个数据。