【发布时间】:2016-09-01 01:46:48
【问题描述】:
简介:
我有 2 个下拉菜单。第二个下拉列表通过 json (json_display.php) 基于第一个下拉列表 (index.html) 的值加载。我已经使用 json - append() 来加载下拉列表。
问题:
json append() 到下拉列表总是按数组键的升序排列。预期结果是以json_display.php 返回的任何数组顺序的格式显示。
- 我有警报 jquery
theResponse,显示错误的排序顺序。 - 我已经尝试将数组键作为整数和字符串,在这两种情况下,输出也是相同的。
注意:
(其实我是在尝试按日期降序检索 mysqli 行并将id => name 存储在数组中并返回)
为简单起见,我已将代码的问题部分提取到index.html 和json_display.php,它们是更大编码的一部分。还将 mysql 检索更改为数组。为了便于说明,名称和所有值都已更改。
图解说明
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#frm").on('change', ' #first_select_box', function(){
var $this = $(this);
var this_val = $this.val();
$('#second_select_box option').not(':eq(0)').remove();
$.ajax({
type : "POST",
url : "json_display.php",
data : { first_select_id: this_val },
dataType : 'json',
success : function(theResponse) {
//alert(JSON.stringify(theResponse));
$.each(theResponse, function(key, value) {
$('#second_select_box')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
});
});
});
</script>
</head>
<body>
<form id="frm" name="frm" method="post" action="#a">
<select id="first_select_box" name="first_select_box">
<option value="0">[First Drop Down]</option>
<option value="1">Numbers</option>
<option value="2">Fruits</option>
<option value="3">Teens</option>
</select>
<select id="second_select_box" name="second_select_box">
<option value="0">[Select]</option>
</select>
</form>
</body>
</html>
json_display.php
<?php
$Array[0] = array();
$Array[1] = array(10 => 'Ten',
9 => 'Nine',
8 => 'Eight',
7 => 'Seven',
6 => 'Six',
5 => 'Five',
4 => 'Four'
);
$Array[2] = array(8 => 'Apple',
1 => 'Orange',
3 => 'Banana',
2 => 'Watermelon',
7 => 'Lemon'
);
$Array[3] = array(17 => 'Seventeen',
11 => 'Eleven',
13 => 'Thirteen',
15 => 'Fifteen',
12 => 'Twelve',
14 => 'Fourteen',
16 => 'Sixteen'
);
$first_select_id = isset($_POST['first_select_id']) ? $_POST['first_select_id'] : 0;
$return_array = $Array[$first_select_id];
echo json_encode($return_array);
?>
【问题讨论】:
-
问题是?????
-
这是浏览器中javascript的行为,你可以将键(值)作为字符串标识符传递吗?这将维持秩序
-
@Thamizhan 你的意思是把钥匙当作字符串吗,我也试过了。
-
@Devs Yes.. 尝试在其上附加一个字符,例如
D1或@1
标签: php jquery json select append