AJAX 调用的 PHP 中的排序数组无效
Ordering array from PHP called by AJAX not working
我现在正在做:
$.ajax({
url: 'full_db.php',
type: 'GET',
dataType: 'JSON',
data: {col_name: firstSel},
success: function(data) {
var full_options = [];
$.each(data, function (i, data) {
full_options.push(data.age);
full_options.sort(function(a, b){
return a.age - b.age;
});
$('#second_select').append("<option>" + data.age + "</option>");
});
}
});
这会将所有不同的年龄附加到我的 select (second_select
) 并且如果我控制台日志 full_options
我明白了:
["55", "98", "34", "30", "45", "29", "26", "22", "37", "42", "32", "33", "36", "35", "56", "46", "25", "54", "86"]
我希望按升序排列(例如:22、25、26、29,...)。
我得到的是无序数组,我做错了什么?
您最好在 PHP 或 MySQL 中的数据进入 JavaScript.
之前对其进行排序
但如果你愿意,你当然可以在 JavaScript.
中对数组进行排序
full_options.sort(); // ascending order [1,2,3]
或者,
full_options.sort();
full_options.reverse(); // descending order [3,2,1]
这是您的表演:
full_options.sort(function(a, b){
return a.age - b.age;
});
这是一种更复杂的方法,它按升序排序。
但是你演错地方了
您的代码应该是:
$.ajax({
url: 'full_db.php',
type: 'GET',
dataType: 'JSON',
data: {col_name: firstSel},
success: function(data)
{
var full_options = [];
$.each(data, function (i, data)
{
full_options.push(data.age);
$('#second_select').append("<option>" + data.age + "</option>");
});
full_options.sort();
}
});
我正在为我发表的评论提供答案。
如果您正在进行数据库调用,请在查询中进行排序
SELECT * from table ORDER BY column_name DESC
我现在正在做:
$.ajax({
url: 'full_db.php',
type: 'GET',
dataType: 'JSON',
data: {col_name: firstSel},
success: function(data) {
var full_options = [];
$.each(data, function (i, data) {
full_options.push(data.age);
full_options.sort(function(a, b){
return a.age - b.age;
});
$('#second_select').append("<option>" + data.age + "</option>");
});
}
});
这会将所有不同的年龄附加到我的 select (second_select
) 并且如果我控制台日志 full_options
我明白了:
["55", "98", "34", "30", "45", "29", "26", "22", "37", "42", "32", "33", "36", "35", "56", "46", "25", "54", "86"]
我希望按升序排列(例如:22、25、26、29,...)。
我得到的是无序数组,我做错了什么?
您最好在 PHP 或 MySQL 中的数据进入 JavaScript.
之前对其进行排序
但如果你愿意,你当然可以在 JavaScript.
full_options.sort(); // ascending order [1,2,3]
或者,
full_options.sort();
full_options.reverse(); // descending order [3,2,1]
这是您的表演:
full_options.sort(function(a, b){
return a.age - b.age;
});
这是一种更复杂的方法,它按升序排序。
但是你演错地方了
您的代码应该是:
$.ajax({
url: 'full_db.php',
type: 'GET',
dataType: 'JSON',
data: {col_name: firstSel},
success: function(data)
{
var full_options = [];
$.each(data, function (i, data)
{
full_options.push(data.age);
$('#second_select').append("<option>" + data.age + "</option>");
});
full_options.sort();
}
});
我正在为我发表的评论提供答案。
如果您正在进行数据库调用,请在查询中进行排序
SELECT * from table ORDER BY column_name DESC