填充下拉菜单使用JSON数据 [英] Populating dropdown menu with JSON Data
问题描述
我tyring使用AJAX来填充基于另一个下拉列表中选择一个下拉框。我也跟着教程使用jQuery设在这里 - HTTP ://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/ ,并已改变在脚本中的选择框名字的选择框ID名称
I'm tyring to use AJAX to populate a dropdown box based on the selection of another dropdown. I followed a tutorial using jQuery located here - http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/ and have altered the select box ID names in the select box names in the script.
当有一个变化的主要复选框AJAX发送的值,并返回如下:
When there's a change to the value of the main checkbox the ajax is sent and returns as below:
{"1":"Kieran Hutchinson","2":"Caleb Tan","3":""}
这是略有不同,在教程code,看起来像这样返回的JSON字符串
THis is slightly different to the JSON string that is returned in the tutorials code which looks like this
[{optionValue:10, optionDisplay: 'Remy'}, {optionValue:11, optionDisplay: 'Arif'}, {optionValue:12, optionDisplay: 'JC'}]
我想这是问题,但我不知道怎么去正确的价值观出了我的JSON响应。
I'm thinking this is the issue but I have no idea how to get the correct values out of my JSON response.
JavaScript的是如下:
The javascript is as below:
$(function(){
$("select#ContactCompanyId").change(function(){
$.getJSON("contactList",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#QuoteContactId").html(options);
})
})
})
在此先感谢
推荐答案
您的问题是这一行:
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
期待在本教程的格式发送数据。你是一个不同的格式。尝试:
is expecting data sent in the format of the tutorial. Yours is a different format. Try:
options += '<option value="' + i + '">' + j[i] + '</option>';
您有'值'作为只是一个索引 - i和值作为与该键,J [I]的值。所以选项标签,你会最终会是这样的:
You have the 'value' as just an index -- i, and the value as the value with that key, j[i]. so the option tag you'd end up with would look like this:
<option value="1">Kieran Hutchinson</option>
要更多地解释:原始数据是这样的格式:
To explain more: the original data was in format like this:
// The tutorial data
array[0]['optionValue'] = 10;
array[0]['optionDisplay'] = 'Remy';
// Your data
array[1] = 'Kieran Hutchinson';
此外,如果这是你的榜样返回的实际数据,你的迭代的(VAR I = 0; I&LT; j.length;我++)
将会失败,因为你是不是开始的0。使用的(我为J){...}
also, if that was actual data returned in your example, your iterator for (var i = 0; i < j.length; i++)
will fail because you aren't starting at an index of 0. Use for(i in j) { ... }
这篇关于填充下拉菜单使用JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!