我似乎不知道如何使用 jQuery 来操作我的 JSON。我有一个 ajax 查询,它使用一些要用作选择选项的键/值对正确回复。
[{"Value":"???","Text":"??? - Unknown"},
{"Value":"AAA","Text":"AAA - A Company"},
{"Value":"BBB","Text":"BBB - B Company"},
{"Value":"CCC","Text":"CCC - C Company"},
{"Value":"DDD","Text":"DDD - D Company"},
{"Value":"EEE","Text":"EEE - E Company"},
{"Value":"FFF","Text":"FFF - F Company"}]
我的jQuery如下
$(function () {
$("#sqlServerControl").change(function () {
var sqlServer = $(this).find(":selected").val();
$.ajax({
url: "http://localhost/ReportGroupsHelper/Ajax/GetOrganisationData.cshtml",
type: "GET",
data: "sqlserver=" + sqlServer,
dataType: "json",
success: function (data) {
var options, index, select, option;
// Get the raw DOM object for the select box
select = $("#organisationControl");
// Clear the old options
if (select.options != null) {
select.options.length = 0;
}
// Load the new options
//options = data.options;
//for (index = 0; index < options.length; ++index) {
// option = options[index];
// select.options.add(new Option(option.text, option.value));
//}
$.each(data, function (key, value) {
select.append($("<option/>", {
value: key,
text: value
}));
});
}
});
});
});
你可以看到我在哪里尝试了不同的方法,现在已经注释掉了。目前它命中 $.each
然后跳过过去。目标控件的 html 只是
<fieldset>
<label for="organisationControl">Organisation</label>
<select name="organisation" id="organisationControl"></select>
</fieldset>
最佳答案
value
不是您在 each()
中查找的值。您需要使用 value.Value
和 value.Text
。
var data = [{"Value":"???","Text":"??? - Unknown"},
{"Value":"AAA","Text":"AAA - A Company"},
{"Value":"BBB","Text":"BBB - B Company"},
{"Value":"CCC","Text":"CCC - C Company"},
{"Value":"DDD","Text":"DDD - D Company"},
{"Value":"EEE","Text":"EEE - E Company"},
{"Value":"FFF","Text":"FFF - F Company"}];
var options, index, select, option;
// Get the raw DOM object for the select box
select = $("#organisationControl");
// Clear the old options
if (select.options != null) {
select.options.length = 0;
}
// Load the new options
//options = data.options;
//for (index = 0; index < options.length; ++index) {
// option = options[index];
// select.options.add(new Option(option.text, option.value));
//}
$.each(data, function (key, value) {
select.append($("<option/>", {
value: value.Value,
text: value.Text
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset>
<label for="organisationControl">Organisation</label>
<select name="organisation" id="organisationControl"></select>
</fieldset>
关于javascript - jQuery each() 的 JSON 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47563778/